如何使用ActiveRecord查找不相关的记录?

时间:2009-07-22 20:23:28

标签: ruby-on-rails activerecord join

我通过连接模型建立了多对多关系。从本质上讲,我允许人们表达对活动的兴趣。

class Activity < ActiveRecord::Base
  has_many :personal_interests
  has_many :people, :through => :personal_interests
end

class Person < ActiveRecord::Base
  has_many :personal_interests
  has_many :activities, :through => :personal_interests
end

class PersonalInterest < ActiveRecord::Base
  belongs_to :person
  belongs_to :activity
end

我现在想知道:哪些活动对某个用户表示了兴趣?这必须包括让其他人感兴趣的活动以及完全没有人感兴趣的活动。

一个成功的(但是无效的)方法是两个单独的查询:

(Activity.all - this_person.interests).first

如何在ActiveRecord中整齐地表达此查询?是否有一个(可靠的,保存良好的)插件抽象查询?

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法是通过where参数使用SQL :conditions子句片段。

例如:

Activity.all(:conditions => ['not exists (select 1 from personal_interests where person_id = ? and activity_id = activities.id)', this_person.id])

完全未经测试,可能无法正常工作,但你明白了。