订购范围DESC的结果

时间:2013-02-16 09:26:37

标签: ruby-on-rails-3 scope

我的帖子模型中有这个范围

scope :tynewydd_posts, :include => :department, :conditions => {"departments.name" => "Ty Newydd"}

我想按照创建的顺序对返回的结果进行排序,因此最新的帖子

我试过

scope :tynewydd_posts, :include => :department, :conditions => {"departments.name" => "Ty Newydd"}.order("posts.created_at DESC")

但我得到未定义的方法顺序:哈希,所以我想我不能在这里使用这个方法?

2 个答案:

答案 0 :(得分:2)

尝试这种方式:

scope :tynewydd_posts, 
      :include => :department, 
      :conditions => {"departments.name" => "Ty Newydd"}, 
      :order => "posts.created_at DESC"

答案 1 :(得分:1)

order是传递给范围的可能选项,如下所示:

scope :tynewydd_posts, :include => :department, :conditions => {"departments.name" => "Ty Newydd"}, :order => "posts.created_at DESC"

甚至更好,正确的Rails 3语法如:

scope :tynewrdd_posts, includes(:department).where('departments.name' => 'Ty Newydd').order('posts.created_at DESC')