2011-11-27 63 views
1

我有一个非常标准的应用程序,由一个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 

(对于好奇:这种方法并因此只要有只有一个用户标记的问题解决了工作,只要你添加第二个,每个用户开始只返回已经解决了这些问题其他用户,而不是那些没有被自己解决)

+0

您需要的关系运算符是半差异又名[反连接(http://en.wikipedia.org/wiki/Relational_algebra#Semijoin_.28。 E2.8B.89.29.28.E2.8B.8A.29)。 – onedaywhen

回答

1

通过朋友:

select * from problems where id not in (select problem_id from completed_problems where user_id = USER_ID)) 

虽然我仍然有兴趣在听,如果有在ActiveRecord的方式来做到这一点。

0

我觉得这样的事情会做到这一点:

Problem.where(["id NOT IN (?)", self.problems.all.map(&:id)])