[英]named_scope and HABTM association
I have a models User 我有模特用户
class User < ActiveRecord::Base
has_many :ratings
has_many :rated_films, :through => :ratings, :source => :film
end
and Films 和电影
class Film < ActiveRecord::Base
has_many :users, :through => :ratings
end
I am looking to find all Films that have not been rated by the specified user, smth like 我正在寻找所有尚未由指定用户评级的电影,例如
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)
I am not that familiar with SQL so am not quite sure if this could be achieved in a named scope. 我对SQL不太熟悉,因此不确定是否可以在命名范围内实现。
Many thanks 非常感谢
Yuriy 尤里
I suppose you have a ratings
table, which is your join
table. 我想您有一个
ratings
表,这是您的join
表。 Right? 对? So you need something like:
因此,您需要类似:
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
And you can use 你可以使用
Film.not_rated_by_user(User.first.id)
Please let me know if it helped. 请让我知道是否有帮助。 I haven't tested!
我还没测试!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.