ruby on rails - Foreign Keys pointing to same Model -
i have user
model
class user < activerecord::base attr_accessible :email, :name has_many :client_workouts end
and clientworkout
model
class clientworkout < activerecord::base attr_accessible :client_id, :trainer_id, :workout_id belongs_to :client, :class_name => user, :foreign_key => 'client_id' belongs_to :trainer, :class_name => user, :foreign_key => 'trainer_id' end
i first want know or if i'm doing wrong when writing associations. ideally want able call query find user's clients workouts user's id matches client_id
or trainer_id
. so...
user.client_workouts.trainer???
this not work rails assumes clientworkout have user_id
column. don't think there way make has_many relation matches 2 columns... instead create method this:
class user < activerecord::base attr_accessible :email, :name has_many :client_workouts, :foreign_key => "client_id" has_many :trainer_workouts, :foreign_key => "trainer_id" def client_and_trainer_workouts clientworkouts.where("client_id = ? or trainer_id = ?", id, id) end end
otherwise create scope on clientworkout model this:
class clientworkout < activerecord::base attr_accessible :client_id, :trainer_id, :workout_id belongs_to :client, :class_name => user, :foreign_key => 'client_id' belongs_to :trainer, :class_name => user, :foreign_key => 'trainer_id' scope :workouts_for_user, lambda {|user| where("client_id = ? or trainer_id = ?", user.id, user.id) } end
you both, , let method on use call scope on clientworkout.
Comments
Post a Comment