2
假设我有一个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})
我已经看到了这一点,但这是有效地同我上面的尝试失败。问题是构建的查询会尝试对'people.position'进行排序而不是'assignments.position',从而导致数据库错误。我会在问题中记下这一点。 – numbers1311407
@ numbers1311407这对我来说很好。我用我的项目中的一个例子更新了我的答案。 – janfoeh
然后这会为你工作(鉴于范围没有定义在关联上,因为你现在有)吗?'Session.last.prospects.merge(AttendanceRequest.sort_by_user)' – numbers1311407