Nested Attributes Forms for Has One

401 views Asked by At

I am trying to use nested attribute forms with a relation that is belongs_to and has_one

I have defined the relations in my model like

class Merchant < ActiveRecord::Base

  has_one :account, dependent: :destroy

class Account < ActiveRecord::Base

  belongs_to :merchant

Controller

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

Error

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

There are 1 answers

0
Emu On BEST ANSWER

The build syntax for has_one association:

@merchant.build_account  # this will work

@merchant.account.build  # this will throw error

Read the has_one association documentation for more details.

Also, You should check if @marchant is found with the given id