簡體   English   中英

是否必須將foreign_key選項與belongs_to和has_many選項同時放置?

[英]Is foreign_key option has to be put as the options of belongs_to and has_many at the same time?

我寫了一些的Ruby-on-Rails代碼和我有關於使用部分問題foreign_key在belongs_to的/的has_many關系。 我有兩種模型,一種是Slogan ,另一種是User 兩者之間的關系是一個標語僅對應一個用戶(belongs_to),一個用戶可以有多個標語記錄(has_many)。 兩種型號的代碼如下

# slogan.rb
class Slogan < ApplicationRecord
  belongs_to :author, class_name: :User, foreign_key: :author_id
end
# user.rb
class User < ApplicationRecord
  has_many :slogans
end

為了維護和語義的方便,我將標語上的關聯名稱更改為author(最初應為用戶),並將foreign_key更改為author_id

我的問題是,如果我還想查看他/她從用戶記錄中獲得的所有標語,是否還應該在用戶模型中添加foreign_key選項?

謝謝!!

我認為您不需要添加任何內容。 但是您可以在Rails中使用雙向關聯。 Active Record提供了:inverse_of選項,因此您可以顯式聲明雙向關聯:

class Author < ApplicationRecord
  has_many :books, inverse_of: 'writer'
end

class Book < ApplicationRecord
  belongs_to :writer, class_name: 'Author', foreign_key: 'author_id'
end

通過使用此功能,您可以按以下方式使用:

a = Author.first
b = a.books.first
a.first_name == b.writer.first_name # => true
a.first_name = 'David'
a.first_name == b.writer.first_name # => true

有關更多信息,請參閱: https : //guides.rubyonrails.org/association_basics.html

在您的錯誤消息中,我看到id是user_id而不是author_id 您可以將表中的ID更改為author_id也可以從標語模型中刪除foreign_key foreign_key約束告訴您的Slogan模型應該在數據庫中尋找author_id列。 它找不到該列,因為它名為user_id

必須User模型中添加 foreign_key選項。

從文檔https://guides.rubyonrails.org/association_basics.html#has-many-association-reference

按照慣例,Rails假定用於保留其他模型上的外鍵的列是該模型的名稱,並添加了后綴_id。

因此,如果您不添加foreign_key選項,Rails會在slogans表上假設您有一個user_id列,這就是您出現此錯誤的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM