ruby on rails how to get latest records from has many relationship -
i new ruby on rails. have problem- how latest records has many relationship in model. code this:
class user < activerecord::base has_many :books end class book < activerecord::base belongs_to :user scope :rating, -> { where(rating: 5) } end
what achieve is: i'd latest (last) book each user , filter books using scope rating. can using each loop (looping through user.books , book.last)- inefficient because have lot of data. have ideas how can this? maybe kind of scope chaining each other?
you can if want avoid writing sql:
class book < activerecord::base scope :latest, -> book_ids_hash = book.group(:user_id).maximum(:id) book_ids = book_ids_hash.values where(id: book_ids) end end
then have is:
book.rating.latest
Comments
Post a Comment