2011-06-15 142 views
2

假設我有一個模型A :: B has_many模型C,我該如何命名外鍵?模型A :: B belongs_to foreign_key

Class A::B 
has_many :c 

Class C 
belongs_to :a_b 

在數據庫中,表C有一列a_b_id。 這不起作用。任何想法我失蹤? ::是我感到困惑的。謝謝!

回答

4

由於B位於不同的命名空間中,因此您需要在類C中指定它。

class C < ActiveRecord::Base 
    belongs_to :a_b, :class_name => "A::B" 
end 

由於您使用a_b_id而不是b_id,你需要在A::B

class A::B < ActiveRecord::Base 
    has_many :c, :foreign_key => "a_b_id" 
end 

指定外鍵或者,你可以使用下面的設置,以避免指定在A::B

class C < ActiveRecord::Base 
    belongs_to :b, :class_name => "A::B" 
end 

class A::B < ActiveRecord::Base 
    has_many :c 
end 

這個外鍵將需要b_id在表C

相關問題