i have following models:
class rating < activerecord::base belongs_to :item belongs_to :user end class item < activerecord::base has_many :ratings end
i want fetch items, , ratings made specific user show current user's rating (if exists!) next each item.
i've tried...
item.includes(:ratings).where('ratings.user_id = ?', user_id)
...but don't give me items no ratings.
my first thought has_many association argument, , pass argument includes method. doesn't seem exist.
how posts , eager loaded association filtered on parameter without doing n+1 queries or loading entities memory?
step 1
make current_user
accessible in model layer (one technique outlined here: https://stackoverflow.com/a/2513456/163203)
step 2
add association condition gets evaluated during run time.
rails 2
class item < activerecord::base has_many :ratings has_many :current_user_ratings, :class_name => "rating", :conditions => 'ratings.user_id = #{user.current_user.try(:id)}' end
rails 3.1 , above
class item < activerecord::base has_many :ratings has_many :current_user_ratings, :class_name => "rating", :conditions => proc { ["ratings.user_id = ?", user.current_user.try(:id)] } end
step 3
item.includes(:current_user_ratings)
Comments
Post a Comment