我有一個非常標準的應用程序,由一個SQL數據庫支持,用戶模型,問題模型和CompletedProblem模型充當兩者之間的連接表。查詢關聯表中沒有匹配ID的行
我試圖創建一個方法,返回一個特定用戶沒有解決的所有問題。然而,我遇到了一堵牆,我很欣賞我的方法應該是什麼樣子的指針。
下面是模型以及我最近(不正確)通過創建此方法。
class User < ActiveRecord::Base
has_many :completed_problems
has_many :problems, :through => :completed_problems
def unsolved_problems
Problem.includes({:wall => :gym}, :completed_problems).
where('completed_problems.user_id != ? OR completed_problems.user_id IS NULL)', self.id)
end
end
class Problem < ActiveRecord::Base
has_many :completed_problems
has_many :users, :through => :completed_problems
end
class CompletedProblem < ActiveRecord::Base
belongs_to :user
belongs_to :problem
end
(對於好奇:這種方法並因此只要有只有一個用戶標記的問題解決了工作,只要你添加第二個,每個用戶開始只返回已經解決了這些問題其他用戶,而不是那些沒有被自己解決)
您需要的關係運算符是半差異又名[反連接(http://en.wikipedia.org/wiki/Relational_algebra#Semijoin_.28。 E2.8B.89.29.28.E2.8B.8A.29)。 – onedaywhen