2010-10-01 28 views
0

我發現軌道的activerecord非常奇怪的行爲。 這發生在rails 2.3.9中,不在rails 3中。奇怪的ActiveRecord行爲 - 根據關聯順序的不同行爲

這裏是你如何重現它。 (或者只是克隆GitHub庫的例子,我創建了:混帳混帳克隆://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 

你可以嘗試一下。在第一個例子中,所有事情都應該如此。第二,它出乎意料地表現出來。

打開腳本/控制檯,並做到:

user = User.new 
user.contact = Contact.new 
user.parent = Parent.new 
user.contact 
=> #<Contact id: nil, created_at: nil, updated_at: nil> 

user = User.new 
user.parent = Parent.new 
user.contact = Contact.new 
user.contact 
=> nil 

任何想法,爲什麼會出現這種情況?這是一個錯誤還是我在這裏錯過了一些東西?

+0

你可以在第二個例子的每一行之間添加user.inspect的輸出嗎? – Pablo 2010-10-02 09:21:14

+0

第二個示例的每行之間的user.inspect始終相同:「#<用戶標識:nil,created_at:nil,updated_at:nil>」 – Sergey 2010-10-03 11:25:54

回答

0

似乎是在模型冗餘...協會似乎有點偏離......

根據實際的外鍵的表在,我會拿出無論是通過還是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