【问题标题】:Nested Attributes Forms for Has OneHas One 的嵌套属性表单
【发布时间】:2016-12-18 03:14:22
【问题描述】:

我正在尝试将嵌套的实体形式与belongs_to 和has_one 的关系使用

我已经在我的模型中定义了关系

class Merchant < ActiveRecord::Base

  has_one :account, dependent: :destroy

class Account < ActiveRecord::Base

  belongs_to :merchant

控制器

def edit
    @merchant = Merchant.find(params[:id])
    @merchant.account.build
    @states = State.form_selector
    @products = Product.all
    @properties = Property.where(property_set_id: 1)
  end

错误

NoMethodError (undefined method `build' for nil:NilClass):
  app/controllers/admin/merchants_controller.rb:32:in `edit'

【问题讨论】:

    标签: ruby-on-rails build relationship nested-attributes


    【解决方案1】:

    has_one 关联的构建语法:

    @merchant.build_account  # this will work
    
    @merchant.account.build  # this will throw error
    

    阅读 has_one 关联documentation 了解更多详情。

    另外,您应该检查是否在给定的id 中找到了@marchant

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多