Rails - 与同一模型的关系

Rails - relation to the same model

模型市场的每个实例都可以有一个超市和一个子市场。 我在市场模型中添加了以下代码。

  has_one :market, as: submarket
  belongs_to :market, as: supermarket

我也创建了一个迁移

  def change
    add_column :markets, :supermarket_id, :integer
  end

但是,我仍然遇到错误:

:in `method_missing': undefined local variable or method `submarket' for #<Class:0x007fda225fac40> (NameError)

您应该在 has_one 上定义 submarket 关联。另外,您在滥用选项。应该是:

has_one :submarket, foreign_key: 'supermarket_id', class_name: 'Market'
belongs_to :market, foreign_key: 'supermarket_id'

如果您想将 'belongs_to' 关联命名为 supermarket 而不是 market,这也很简单:

belongs_to :supermarket, foreign_key: 'supermarket_id', class_name: 'Market'

您需要设置自加入:

has_one :submarket, class_name: "Market", foreign_key: :supermarket_id
belongs_to :supermarket, class_name: "Market", foreign_key: :supermarket_id