2016-09-07 41 views
0

讓我們考慮下面的模型。在同一模型中創建has_one關聯

User{ id:number(primary_key), column1:string, column2:string) 

現在,column1可以是任何字符串,但column2可以是null,也可以是來自column1的值。但是,column1和column2不能相同。 I.E. column2將是外鍵,它將引用column1。

我將如何創建與這些約束的has_one關係。

喜歡的東西,

has_one :master_agreement, :class_name => 'User', :foreign_key => 'column2', :primary_key => 'column1' 

但提到我不工作上面。

+1

如果您需要自聯接的外鍵值,那麼引用表的id會更有意義,不是嗎? –

+0

實際上這必須工作 –

回答

0

要設置在軌自加盟關係,要使用belongs_tohas_one的關鍵區別在於belongs_to地對模型的表的外鍵列 - 而has_one其放在另一端。

class User < ActiveRecord::Base 
    belongs_to :company # references users.company_id 
    has_one :company # references companies.user_id 
end 

讓我們考慮一個系統,如果你有類別的層次結構:

class Category < ActiveRecord::Base 
    belongs_to :parent, class_name: 'Category' 
    has_many :subcategories, class_name: 'Category', foreign_key: 'parent_id' 
end 

這將創建與引用categories.idcategories.parent_id外鍵列自加盟關係。

儘管您可能會使用與categories.id不同的東西作爲參考,但您只是將自己的工作變得更加困難,因爲id列已經是索引主鍵列。

相關問題