Shortcut to indicate the order and restrictions when accessing the has_many relation?

Is there a shortcut to indicate the limit and order when accessing the has_many relation in the ActiveRecord model?

For example, here is what I would like to express:

@user.posts(:limit => 5, :order => "title") 

Unlike the longer version:

 Post.find(:all, :limit => 5, :order => "title", :conditions => ['user_id = ?', @user.id]) 

I know that you can specify it directly in the has_many relationship, but is there a way to do this on the fly, for example, showing 10 posts on one page, but only 3 on another?

+3
source share
3 answers

I have something similar on the blog:

  has_many :posts, :class_name => "BlogPost", :foreign_key => "owner_id", :order => "items.published_at desc", :include => [:creator] do def recent(limit=3) find(:all, :limit => limit, :order => "items.published_at desc") end end 

Using:

 Blog.posts.recent 

or

 Blog.posts.recent(5) 
+8
source

You can do this using the named scope in the post model:

 class Post < ActiveRecord::Base named_scope :limited, lambda {|*num| {:limit => num.empty? ? DEFAULT_LIMIT : num.first}} end 

This is essentially similar to utility_scopes, as @Milan reported, except that you make this piece of food, only where you need to do it.

+3
source

You can use Ryan Daigle utility_scopes . After installation (this is a gem), you will receive new useful areas, such as:

 @user.posts.ordered('title ASC').limited(5) 

You can even set default order and restrictions for any model.

+1
source

All Articles