Can I add the limit the result of object return in Ruby on rails?
For Example, I want to know the User have many posts. So, I can get back post using this :
@user.posts
but I don't want to get 开发者_如何学运维all the posts back. I would like to limite the result, for example, top ten created, or may be sorted by some column. How can I do so? Thank you.
You can always make a generic scope to handle the limit, such as putting this in an initializer:
class ActiveRecord::Base
named_scope :limit, lambda { |*limit| {
:limit => limit[0] || 10,
:offset => limit[1]
}}
end
This makes limiting queries easy:
# Default is limited to 10
@user.posts.limit
# Pass in a specific limit
@user.posts.limit(25)
# Pass in a specific limit and offset
@user.posts.limit(25, 25)
For something more robust, you might want to investigate will_paginate.
Try this:
@user.posts(:limit => 10, :order => "created_at DESC")
http://guides.rubyonrails.org/active_record_querying.html
You should take a look at the options available for the has_many
association.
You could try something like this:
class User < ActiveRecord::Base
has_many :posts
has_many :top_ten_posts, { :class_name => "Post", :order => :some_rating_column, :limit => 10 }
end
精彩评论