Ask A Question

Notifications

You’re not receiving notifications from this thread.

Was wondering id there is a way i can simply this ...

Alan Reid asked in Rails

I was wondering if there is any way I can simplify this code, Ideally, I don't want to be looking up brands that are associated with the user, i want to do it on hit.

#Gets the ID associated to the current user
brand_ids = current_user.brands.pluck(:id)

#Looks up the articles associated with this user.
@articles_count = Article.where(brand_id: brand_ids)

Thanks in advance

Reply

You can set up the association on the user to has_many through:

class User
  has_many :brands
  has_many :articles, through: :brands
end

And then you can access them directly and it will be auto-scoped for you:

current_user.articles
Reply

Cheers buddy. haha you know when you spend so long looking at the code you mind just goes blank :o lol

Reply

Psh, that only happens like once every... day. 🤓

Reply

your telling me!

I been added likes to my app, now i am adding follows using a variant of the code you showed for the likes. And now for some reason i can't get the JS bit to work haha you have to refresh the page for the follow to register.

Reply

You can inspect the JS response in the Network tab in the console and then copy paste that into the Javascript console. Might be a typo or something simple.

Reply

would this be the same if i wanted to get a variants volume type?
Would i need to add , through: : products on the has_one :volume_types in the product_variant model

I have the following...

Product Model

product
has_many :product_variants, dependent: :destroy

Variant Model

product_variant
belongs_to :product
has_one :volume_types

# table has: volume_type_id

Volume Type Model

volume_type
belongs_to :product_variant

#table: volume_types
#t.string "short_name"
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.