【问题标题】:rails 4 belongs_to and has_many to the same modelrails 4 belongs_to 和 has_many 属于同一模型
【发布时间】:2020-02-24 14:49:48
【问题描述】:

我有一个属于_to Section 模型的 Opportunity 模型。 部分有_很多机会。

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】:

    您需要在OpportunitySection 之间建立多对多关联,为此您需要在两者之间创建连接表,创建迁移

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

    然后在Opportunity模型中,添加这一行

    has_and_belongs_to_many :sections
    

    Section 模型中,添加这一行

    has_and_belongs_to_many :opportunities
    

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

    更多关于has_and_belongs_to_many协会的信息在这里

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

    您也可以通过has_many through关联实现many-to-many关联,has_and_belongs_to_manyhas_many through的基本区别是您可以为连接表创建一个模型类,这样您就可以在保存方面获得更大的灵活性连接的任何附加数据。更多信息在这里

    https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

    选择什么?

    https://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many

    Rails 指南找到了所有答案!

    【讨论】:

    • 也许还添加has_many :through 选项并解释差异...
    • 感谢您的详细解答。
    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多