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

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -