2010-08-12 93 views
1

我有一個模型用戶named_scope和HABTM協會

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

這是最初發布後很久,但有一個答案可能有所幫助:http://stackoverflow.com/questions/7032194/rails-habtm-and-finding-record-with-no-association – ScottJShea 2013-07-08 23:09:13

回答

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) 

請讓我知道,如果它幫助。我沒有測試!

+0

它執行沒有錯誤但不會產生預期結果 – Yuriy 2010-08-12 19:25:51

+0

結果如何? – 2010-08-12 19:37:28

+0

>> Film.not_rated_by_user(User.first.id) => [] – Yuriy 2010-08-12 19:38:44