一系列联合协会订购的正确方法是什么?

时间:2013-12-11 14:09:32

标签: ruby-on-rails ruby-on-rails-4

说我有一个has_many :through关联。连接模型定义了正确的顺序,我需要对其进行排序。我怎样才能对这个订单进行排序,让它干嘛?

例如,一个人拥有并属于许多任务,由任务加入和排序:

class Person
  has_many :assignments
  has_many :tasks, through: assignments
end

class Assigment
  belongs_to :person
  belongs_to :task
  scope :ordered, ->{ order(position: :asc) }
end

我如何利用该范围来命令该人的任务?

# Something like this would be nice, but unfortunately this generates a database
# query attempting to order on `people.position`, not `assignments.position`
person.tasks.merge(Assignment.ordered)

# So the less than ideal solution is to repeat myself
person.tasks.order(assignment: {position: asc})

1 个答案:

答案 0 :(得分:0)

原来你可以:

class Person
  has_many :assignments
  has_many :tasks,
           -> { merge(Assignment.ordered) },
           through: :assignments
end

纯;我不知道。在我的应用中,我有

class Session < ActiveRecord::Base
  has_many :attendance_requests
  has_many :users, 
            -> { merge AttendanceRequest.sort_by_user },
            :through    => :attendance_requests
end

当我致电Session.last.prospects时,AR会产生

SELECT "users".*
FROM   "users"
       inner join "attendance_requests"
               ON "users"."id" = "attendance_requests"."user_id"
WHERE  "attendance_requests"."session_id" = $1
ORDER  BY "attendance_requests"."user_id" ASC