ruby on rails - Mutiple has_one of the same class -
got interesting situation has_one
, belongs_to
relationships when rails loads dependant models in inversed manner.
let have model couple
2 related models of same class, user
:
class couple < activerecord::base has_one :male, class_name: "user" has_one :female, class_name: "user" end class user < activerecord::base belongs_to :couple end
in situation, when create couple
, assign 2 instances of user
, this:
# create stuff couple = couple.new = user.create name: 'bob' = user.create name: 'sara' couple.male = couple.female = couple.save # here's gap begins: couple.male.name # => 'bob' couple.female.name # => 'sara' # ok, far good... couple.find(couple.id).male.name # => 'bob' # what's ..?! couple.find(couple.id).female.name # => 'bob'
and i've seen in console performing these, this:
> couple.female.name 'sara' # nothing happens model loaded > couple.find(couple.id).female.name select `couples`.* `couples` `couples`.`id` = 2 limit 1 select `users`.* `users` `users`.`couple_id` = 2 limit 1 'bob' # sure, here's trouble!
hmmm... that's not good... searching on internet guided me this: created 2 classes, maleuser
, femaleuser
, both derived user
model. , changed belongs_to :couple
belongs_to :couple, foreign_key: :his_id
, ... :her_id
. yet, same result seen on screen.
my question is, why hell happens , how perform loading in correct manner? couple.find(couple_id).she
gave me proper object?
upd: tables structure:
create_table :users |t| t.integer :couple_id # ... end create_table :couples |t| t.integer :his_id t.integer :her_id # ... end
thanks!
the relationship users
in couple
needs belongs_to
relationship , not has_one
. e.g:
class couple < activerecord::base # ... belongs_to :male, :class_name => 'user', :foreign_key => 'his_id' belongs_to :female, :class_name => 'user', :foreign_key => 'her_id' end
this tells activerecord couple
has 2 user
object relations. 1 named male
can retrieved id found in his_id
column of couple table , 1 named female
who's id found in her_id
column.
whereas has_one
relationship data on users
table (which doesn't exist). users table references couple_id
, not whether user male or female user couple
relationship.
Comments
Post a Comment