Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 什么';按加入的协会范围排序的正确方式是什么?_Ruby On Rails_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 什么';按加入的协会范围排序的正确方式是什么?

Ruby on rails 什么';按加入的协会范围排序的正确方式是什么?,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,假设我有一个有很多:通过关联。联接模型定义了正确的顺序,我需要对其进行排序。我怎样才能在订单上分类,保持干燥 例如,假设一个人拥有并属于许多任务,并通过分配加入和排序: class Person has_many :assignments has_many :tasks, through: assignments end class Assigment belongs_to :person belongs_to :task scope :ordered, ->{ or

假设我有一个
有很多:通过
关联。联接模型定义了正确的顺序,我需要对其进行排序。我怎样才能在订单上分类,保持干燥

例如,假设一个人拥有并属于许多任务,并通过分配加入和排序:

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})
事实证明你可以:

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

我已经看到了这一点,但这实际上与我上面失败的尝试相同。问题是,生成的查询将尝试按
人员.position
而不是
assignments.position
排序,从而导致数据库错误。我会在问题中记下的。@1311407这个对我来说很好。我已经用我的项目中的一个例子更新了我的答案。这对你有用吗(考虑到范围没有像你现在这样在关联中定义)?
Session.last.prospects.merge(AttendanceRequest.sort\u by\u user)
是的,我得到了相同的结果。奇怪的是,我必须稍后再回到这个问题,并进一步测试。我的应用程序非常普通,但当我做完全相同的事情时,正如我所说的,SQL生成错误。我正在使用postgres,我想适配器可能是一个因素?你的数据库是什么?
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