Question

I have a model where an article can have multiple tags (and a tag multiple articles). Article has two subclasses, product and kit. Products have a category, kits have not.

How can I get all articles (both kits and products) of a certain tag (I know the tag.id) , with the product's category loaded (avoiding a n+1)?

Was it helpful?

Solution

Assuming your associations are already setup (i.e. tag has_many :articles through article_tags, etc.), if you're using Rails 3, you can use #includes when you do your find. Move your belongs_to :category to your Article class (yes, it's semantically okay to do so), then:

@tag = Tag.first
@tag.articles.includes(:category)

Should work.

http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top