rails 4属于同一模型的has_many

问题描述 投票:0回答:1

我有一个Opportunity模型,它属于Section模型。本节有很多机会。

class Opportunity < ActiveRecord::Base

  belongs_to :section
class Section < ActiveRecord::Base

  has_many :opportunities

机会模型必须具有section_id,但在某些情况下,我希望能够将许多部分作为涉及的部分。

如何创建?谢谢

ruby-on-rails ruby-on-rails-4 has-many has-and-belongs-to-many belongs-to
1个回答
0
投票

您需要OpportunitySection之间的多对多关联,创建迁移

create_table :opportunities_sections, id: false do |t|
  t.belongs_to :opportunity
  t.belongs_to :section
end

在机会模型中,

has_and_belongs_to_many :sections

在截面模型中,

has_and_belongs_to_many :opportunities

最后,从section_id表中删除opportunities列。

有关has_and_belongs_to_many关联的更多信息,请点击此处>>

https://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

© www.soinside.com 2019 - 2024. All rights reserved.