簡體   English   中英

has_many和belongs_to模型rails

[英]has_many and belongs_to models rails

我需要創建2個模型:作者和書籍。

表格書籍將包含4列:

  • first_author:int#將使用Authors_id填充
  • second_author:int#將使用Authors_id填充
  • third_author:int#將使用Authors_id填充
  • Fourth_author:int#將填充有Authors_id

我不能使用has_many :books因為表格Books不會包含Authors_id列。

我需要書籍和作者之間的哪種關聯? 還是根本不需要創建關系並在必要時創建獲取Authors_id的方法?

您可以使用聯接表:

rails g model BookAuthors book_id:references author_id:references

然后在您的Book模型中

has_many :authors, :through => :BookAuthors

並在您的作者模型中

has_many :boooks, :through => :BookAuthors

您可以在此處了解有關關聯的更多信息: http : //guides.rubyonrails.org/association_basics.html他們甚至使用book / author示例:)

您想要做的就是告訴rails first_author和second_author等都將引用一個作者。 因為這不是通常的rails約定,所以我們將外鍵傳遞給模型關聯以告知它。

在您的圖書模型中:

has_one :first_author, foreign_key: "author_id"
has_one :second_author, foreign_key: "author_id"
has_one :third_author, foreign_key: "author_id"
has_one :fourth_author, foreign_key: "author_id"

在您的作者模型中:

has many :books

暫無
暫無

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

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