I am new to Ruby on Rails. I have a problem- how to get only latest records from has many relationship in model. My code is like this:
class User < ActiveRecord::Base
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :user
scope :rating, -> { where(rating: 5) }
end
What I would like to achieve is: I'd like to get all latest (last) book for each user and than filter this books using scope rating. I can do this using for each loop (Looping through User.books and get book.last)- but this is very inefficient because I have a lot of data. Do you have any ideas how I can do this? maybe some kind of scope chaining with each other?
You can do this if you want to avoid writing SQL:
class Book < ActiveRecord::Base
scope :latest, -> do
book_ids_hash = Book.group(:user_id).maximum(:id)
book_ids = book_ids_hash.values
where(id: book_ids)
end
end
Then all you have to do is:
Book.rating.latest
Try this:
User.find_each do |user|
puts 'User top 10 books:'
user.books.rating.order('id DESC').limit(10).each do |book|
puts book.title
end
end
I'd like to get all latest (last) book for each user
In the example above, note the .order('id DESC').limit(10)
. This will sort books by ID in descending order.
每位用户一本书,然后将结果限制为评分为5的用户,一个查询无循环或任何问题。
Book.order(created_at: :desc).group(:user_id).rating
Just use last
method and pass the number of records you want to the parameter :
user.books.last(5).rating
this will give you the 5 last books and apply the rating to it.
see http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-last
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.