访问has_many关系时指定订单和限制的快捷方式?

Mic*_*cah 3 activerecord ruby-on-rails

在ActiveRecord模型中访问has_many关系时是否有提供限制和顺序的快捷方式?

例如,这是我想表达的内容:

@user.posts(:limit => 5, :order => "title")
Run Code Online (Sandbox Code Playgroud)

与较长版本相反:

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

我知道你可以直接在has_many关系中指定它,但有没有办法在运行中做到这一点,例如在一个页面上显示10个帖子,但在另一个页面上只显示3个帖子?

Dus*_*tin 8

我在博客模型中有类似的东西:

  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
Run Code Online (Sandbox Code Playgroud)

用法:

Blog.posts.recent
Run Code Online (Sandbox Code Playgroud)

要么

Blog.posts.recent(5)
Run Code Online (Sandbox Code Playgroud)