RoR: nested attributes undefined method `build

603 views Asked by At

i'm trying to put in the "client" form an nested fields_for to add his address at same time. Followed this video: https://www.youtube.com/watch?v=fsgTT9hizZo which shows what i need.

well this is my code:

cliente model =>

class Cliente < ActiveRecord::Base

 has_one :local
 accepts_nested_attributes_for :local


end

local model=>

class Local < ActiveRecord::Base
 belongs_to :cliente


end

cliente controller =>

def new
 @cliente = Cliente.new
 @cliente.build_local
end
def cliente_params
  params.require(:cliente).permit(:name, :telefone, :celular, :email, :local_attributes => [:logra, :cep, :uf, :city, :km])
end

cliente view

  <%= f.fields_for :local do |ff| %>

  <td>   <%= ff.text_field :km %> </td>

And the error = undefined method `build_local' for # in the cliente_controller.rb

2

There are 2 answers

1
Darpa On BEST ANSWER

Give this a try-

@cliente.build_local()

instead of -

@cliente.build_local
1
Prashant4224 On

Before creating the local object, You first need to create cliente object

def new
  @cliente = Cliente.new      
end

def show
  @cliente = Cliente.find(params[:id])
  @cliente.build_local
end