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

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

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

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

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"
Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.