我有模特用户
class User < ActiveRecord::Base
has_many :ratings
has_many :rated_films, :through => :ratings, :source => :film
end
和电影
class Film < ActiveRecord::Base
has_many :users, :through => :ratings
end
我希望找到所有未被指定用户评分的电影,如
class Film < ActiveRecord::Base
has_many :users, :through => :ratings
named_scope :not_rated_by_user, lambda { |user|
{:joins => :users, :conditions => ['? NOT IN users', user]}
}
end
Film.not_rated_by_user(User.first)
我不熟悉SQL,所以我不太确定是否可以在命名范围内实现。
非常感谢
尤里
答案 0 :(得分:0)
我想你有一个ratings
表,这是你的join
表。对?所以你需要这样的东西:
class User < ActiveRecord::Base
has_many :ratings
has_many :rated_films, :through => :ratings, :source => :film
end
class Film < ActiveRecord::Base
has_many :ratings
has_many :users, :through => :ratings
named_scope :not_rated_by_user, lambda { |user_id| {
:include => :ratings,
:conditions => ['? NOT IN (ratings.user_id)', user_id]
}}
end
class Rating < ActiveRecord::Base
belongs_to :film
belongs_to :user
end
你可以使用
Film.not_rated_by_user(User.first.id)
如果有帮助,请告诉我。我没有测试过!