2013-12-11 43 views
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}) 

回答

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 
+0

我已經看到了這一點,但這是有效地同我上面的嘗試失敗。問題是構建的查詢會嘗試對'people.position'進行排序而不是'assignments.position',從而導致數據庫錯誤。我會在問題中記下這一點。 – numbers1311407

+0

@ numbers1311407這對我來說很好。我用我的項目中的一個例子更新了我的答案。 – janfoeh

+0

然後這會爲你工作(鑑於範圍沒有定義在關聯上,因爲你現在有)嗎?'Session.last.prospects.merge(AttendanceRequest.sort_by_user)' – numbers1311407

相關問題