2016-12-16 74 views
2

有人可以解釋我是我的代碼是正確的。在rails關聯中使用foreign_key has_many

我想在rail協會中獲得foreign_key選項。

我有型號: 作者

簿數據庫架構:

  • USER_ID

作者DB模式:

我的模型:

class Author < ApplicationRecord 
    has_many :books, foreign_key: :user_id 
end 

class Book < ApplicationRecord 
    belongs_to :author, foreign_key: :user_id 
end 

在這裏,我不明白爲什麼我們要在兩個模型定義foreign_key。是否一定?

回答

3

如果您已經使用了Rails期望的表名列名,那麼您不需要明確定義foreign_key。在你的情況下,如果外鍵列被命名爲author_id,那麼你就可以得到由很簡單:

class Author < ApplicationRecord 
    has_many :books 
end 

class Book < ApplicationRecord 
    belongs_to :author 
end 

然而,在你的情況下,外鍵列未命名的根據是什麼Rails的預計,所以你必須需要明確定義外鍵列名稱。這很好,但它確實爲你做了更多的工作。

如果您已經明確定義了外鍵,則應該爲兩個關聯定義它。沒有它,你的has_many協會將無法正常工作。

此外,你應該定義的負相關關係:

class Author < ApplicationRecord 
    has_many :books, foreign_key: :user_id, inverse_of: :author 
end 

class Book < ApplicationRecord 
    belongs_to :author, foreign_key: :user_id, inverse_of: :books 
end 

定義inverse_of可能導致的ActiveRecord,使更少的查詢,並擺脫了幾個奇怪的行爲。有關inverse_of的解釋,請參閱Ryan Stenberg的Exploring the :inverse_of Option on Rails Model Associations

+0

好的。你的意思是模型作者(沒有定義foreign_key)會在表格書中尋找author_id字段。這就是爲什麼我們應該明確定義foreign_key? –

+0

@DorianG這是正確的。我已經添加了答案。 –

+1

@WayneConrad非常感謝!在找到答案之前,我通過嚴格的測試發現了自定義外鍵的效果。現在我可以真正感受到這種情況!希望你關心':inverse_of'選項的其他問題肯定會節省很多努力:)想知道爲什麼這不是在rails guide/api :( –