# User.rb
def most_wanted_movies
movie_parent_ids = UserInterest.find(:all,:select=>"parent_id",:conditions=>"user_id = #{self.id} and parent_type = 'Movie' and interested = 1 ").collect{|m| m.parent_id}
Movie.find(movie_parent_ids)
end
Refactorings
No refactoring yet !
mainej
May 24, 2009, May 24, 2009 03:33, permalink
Looks like you want a polymorphic has many through relationship, which Rails allows. Below is some code, and the SQL it runs. The named scope on Movie is a bit of a hack - maybe there's a better way.
class UserInterest < ActiveRecord::Base belongs_to :parent, :polymorphic => true belongs_to :user end
class User < ActiveRecord::Base
has_many :user_interests
has_many :movies, :through => :user_interests, :source => :parent, :source_type => 'Movie'
def most_wanted_movies
movies.most_interesting
end
end
class Movie < ActiveRecord::Base
named_scope :most_interesting, :conditions => {'user_interests.interested' => 1}
end
SELECT "movies".*
FROM "movies"
INNER JOIN "user_interests"
ON "movies".id = "user_interests".parent_id
AND "user_interests".parent_type = 'Movie'
WHERE
(("user_interests".user_id = 5)) AND
(("user_interests"."interested" = 1) AND
(("user_interests".user_id = 5))) -- not sure where the duplication comes from
dive.myopenid.com
June 22, 2009, June 22, 2009 19:13, permalink
Also put your attention to your quoting / SQL injection!
from http://api.rubyonrails.org/classes/ActiveRecord/Base.html
class User < ActiveRecord::Base
def self.authenticate_unsafely(user_name, password)
find(:first, :conditions => "user_name = '#{user_name}' AND password = '#{password}'")
end
def self.authenticate_safely(user_name, password)
find(:first, :conditions => [ "user_name = ? AND password = ?", user_name, password ])
end
def self.authenticate_safely_simply(user_name, password)
find(:first, :conditions => { :user_name => user_name, :password => password })
end
end
Hay Guys
Following code goes in the User model.
Is there another way to write following code more efficiently and scalable ?