在Active Record中订购关联以覆盖关联中定义的默认排序顺序

时间:2015-09-08 14:35:30

标签: ruby-on-rails activerecord

所以我有一个叫做代理的课程,在那个课程中我有以下内容:

class Agency
  has_many :users,  order: 'last_name ASC, first_name ASC'
end

而且,当我执行以下操作时:

irb(main):004:0> agency.users.order('active desc').pluck(:active)

并生成以下内容

  SQL (22.0ms)  SELECT "users"."active" FROM "users" WHERE "users"."agency_id" = 4040 ORDER BY last_name ASC, first_name ASC, active desc

所以,我想要的是覆盖代理类中的顺序,而不是按last_name或first_name排序。我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

使用reorder

agency.users.reorder('active desc').pluck(:active)

生成的SQL将是

SELECT "users"."active" FROM "users" WHERE "users"."agency_id" = 4040 ORDER BY active desc

来自指南,

  

重新排序方法会覆盖默认范围顺序,例如:

class Article < ActiveRecord::Base
  has_many :comments, -> { order('posted_at DESC') }
end

Article.find(10).comments.reorder('name')

将执行的SQL:

SELECT * FROM articles WHERE id = 10
SELECT * FROM comments WHERE article_id = 10 ORDER BY name

如果未使用reorder子句,则执行的SQL将为:

SELECT * FROM articles WHERE id = 10
SELECT * FROM comments WHERE article_id = 10 ORDER BY posted_at DESC