1

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.

Many thanks

Yuriy

Jamie Wong
  • 18,104
  • 8
  • 63
  • 81
Yuriy
  • 11
  • 1
  • Long after this was originally posted but there is an answer here that may help: http://stackoverflow.com/questions/7032194/rails-habtm-and-finding-record-with-no-association – ScottJShea Jul 08 '13 at 23:09

1 Answers1

0

I suppose you have a ratings table, which is your join table. 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!

Ju Nogueira
  • 8,435
  • 2
  • 29
  • 33