Topic: Model Association: Brain Failure
If someone can help with my models, I'd be very greatful. I get the feeling I need a cunning association that I don't have.
Ok, to simplify: I have a table of ITEMS which live in CATEGORIES. USERS log into the site, and may possible have FAVOURITE_ITEMS. That's about it.
class Item < ActiveRecord::Base
class Category < ActiveRecord::Base
class User < ActiveRecord::Base
class Favourite_Items < ActiveRecord::Base
Now, my user is all logged in, and has selected a category, so in my controller I have:
@u = User.find(1) # Really comes from the session
@c = Category.find(1)
@i = @c.items
And in my view, I simply use a partial to display the items.
<%= render(:partial => "items", :collection => @i) %>
So far so good.
Now, what I want to do is put a nice star (or something!) next to the users favourite items -- ideally by using lovely railsish <% if @i.favourite_for_user?(@u.id) %>, but if I placed this code into the Item model, how would I avoid doing 1 SQL query for each item?
I thought about trying to :include => 'favourite_items' when finding the items in my controller code, but I would then include everyone's favourite items, not just the currently logged in user.
Hopefully I'm making some kind of sense. Any pointers will be greatly appreciated.