Odd ActiveRecord behavior - behaves differently based on order of associations
I've found pretty odd behavior of rails's activerecord. This occurs in rails 2.3.9 and does not in rails 3.
Here is how you can reproduce it. (Or just clone github repo example I created: git clone git://github.com/gonchs/rails-2.3.9-odd-association-behavior-example.git )
class User < ActiveRecord::Base
has_one :parent
has_one :contact, :through => :parent
end
class Contact < ActiveRecord::Base
has_one :parent
has_one :user, :through => :parent
end
class Parent < ActiveRecord::Base
belongs_to :user
belongs_to :contact
end
Try it for yourself. In the first example, everything goes as it should. In the second, it behaves unexpectedly.
open up script/console and do:
user = User.new
user.contact = Contact.new
user.parent = Parent.new
u开发者_运维问答ser.contact
=> #<Contact id: nil, created_at: nil, updated_at: nil>
user = User.new
user.parent = Parent.new
user.contact = Contact.new
user.contact
=> nil
Any ideas why is this happening? Is it a bug or am I missing something here?
There seems to be redundancy in the models... the associations seem a little off...
Depending on where the actual foreign keys are in the tables, I would take out either the through or has_one...
class User < ActiveRecord::Base
has_one :parent
end
class Contact < ActiveRecord::Base
has_one :user, :through => :parent
end
class Parent < ActiveRecord::Base
belongs_to :user
belongs_to :contact
end
精彩评论