ruby on rails - Include associated model for all objects (in index action) -


i trying develop ratings application, user able set specific rating comment. have followed following tutorial in order so.

here associations:

class rating < activerecord::base   belongs_to :comment   belongs_to :user end  class comment < activerecord::base   has_many :ratings   belongs_to :user end  class user < activerecord::base   has_many :ratings   has_many :comments end 

my problem here that, in index action of comments controller, need include rating user has done comment. in tutorial shown how select particular rating doing this:

@rating = rating.where(comment_id: @comment.id, user_id: @current_user.id).first   unless @rating    @rating = rating.create(comment_id: @comment.id, user_id: @current_user.id, score: 0)  end 

however, have several ratings, because in controller have:

def index   @comments = @page.comments #here each comment should have associated rating current_user, or newly created rating if not exist. end 

you want find comment's rating rating's user_id matches current user.

<%= comment.ratings.where(user_id: current_user.id).first %> 

however sort of logic pretty cumbersome in views, better strategy define scope in rating returns ratings made specific user.

class rating   scope :by_user, lambda { |user| where(user_id: user.id) } end  class comment   # return either rating created given user, or nil   def rating_by_user(user)     ratings.by_user(user).first    end end 

now in view, have access rating comment created current user:

<% @comments.each |comment| %>   <%= comment.rating_by_user(current_user) %> <% end %> 

if want eager load ratings in index page, can following:

def index   @comments = page.comments.includes(:ratings) end 

you can find correct rating following:

<% @comments.each |comment| %>   <%= comment.ratings.find { |r| r.user_id == current_user.id } %> <% end %> 

this return correct rating without generating sql queries, @ expense of loading every associated rating each comment.


i'm not aware of way in activerecord eager load subset of has_many relationship. see this related stackoverflow question, this blog post contains more information eager loading.


Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -