Rails - 与同一模型的关系

时间:2015-05-20 10:40:52

标签: ruby-on-rails migration

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

  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)

2 个答案:

答案 0 :(得分:2)

您应该在DashboardModel上定义[Bind(Include = "DashID,DashName,CreatedBy,CreatedDate")] public class DashboardModel { // ... } 关联。此外,你误用了选项。它应该是:

submarket

如果您希望将'belongs_to'关联命名为has_one而不是has_one :submarket, foreign_key: 'supermarket_id', class_name: 'Market' belongs_to :market, foreign_key: 'supermarket_id' ,那么也很容易:

supermarket

答案 1 :(得分:2)

您需要设置自我加入:

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