ruby on rails - Multiple References From Single Table -
ruby on rails - Multiple References From Single Table -
i've seen issue referenced few times, nil complete. i'm having problem using bring together table single model. example, suppose have users , highfives. highfives bring together table 2 users highfiving. have this:
class highfive < activerecord::base belongs_to :user1, :class_name => "user" belongs_to :user2, :class_name => "user" end class user < activerecord::base has_many :highfives end
however, this, unable user.find(1).highfives since generates query like:
select "highfives".* "highfives" "highfives"."user_id" = 1
really, should getting query like:
select "highfives".* "highfives" "highfives"."user1_id" = 1 or "highfives"."user2_id" = 1
i imagine i'll need modify user model in way. missing?
thanks.
you need specify foreign key in has_many
statement, otherwise rails assume it's user_id
:
class user < activerecord::base has_many :highfives, :foreign_key => :user1_id end
of course, works single foreign key. in case, you'd want instance method instead:
class user < activerecord::base def highfives highfive.where("user1_id = ? or user2_id = ?", id, id) end end
or, assuming it's impossible user
highfive himself:
class user < activerecord::base has_many :highfives1, :class => "highfive", :foreign_key => :user1_id has_many :highfives2, :class => "highfive", :foreign_key => :user2_id def highfives highfives1 + highfives2 end end
ruby-on-rails ruby activerecord
Comments
Post a Comment