views:

47

answers:

1

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)?

A: 

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

jenjenut233
Unfortunately, it does not. Association named 'categories' was not found; perhaps you misspelled it? Articles have no categories, only products do.
Jan Limpens
ah, I see, you put categories to articles first, but this would be semantically correct, but not domain wise. Kits consist of multiple articles, which can have different categories in return.
Jan Limpens
Can you post your model code for Article, Product and Kit?
jenjenut233
What I did in the end, was pre fetching all categories (they are few) and then have the 1st level cache deal with the n+1. Works without a problem. Maybe not the best thing to do, but seems to perform ok.
Jan Limpens