Skip to main content
Ask A Question
You’re not receiving notifications from this thread.

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

Rails • Asked by Alan Reid

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

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

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

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


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

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

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.

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.

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

has_many :product_variants, dependent: :destroy

Variant Model

belongs_to :product
has_one :volume_types

# table has: volume_type_id

Volume Type Model

belongs_to :product_variant

#table: volume_types
#t.string "short_name"

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 31,353+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.