views:

42

answers:

3

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.

+1  A: 

Try this:

@user.posts(:limit => 10, :order => "created_at DESC")

http://guides.rubyonrails.org/active_record_querying.html

Jarrod
A: 

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
jigfox
But sometime, I want all, some time I would like to want first 10, sometime is first 20. Can I pass a "filter" in get the result I want??
Tattat
@Tattat: You could use multiple associations similar to the concept of named scopes.
jigfox
+1  A: 

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.

tadman