accepts_nested_attributes_for no Rails 4

Asked

Viewed 240 times

0

Expensive!

I’m having a hard time because I’m new in Rails.

I am trying to generate a form with two models through Nested Form Rails. It is a simple model.

"Motor" has one or more "parts", and "part" has only one "engine". In this way I made the models:

 class Motor < ActiveRecord::Base
   has_many :pecas
   accepts_nested_attributes_for :pecas
 end

 class Peca < ActiveRecord::Base
   belongs_to :motor
 end

The "Motors" controller is :

  def new
    @motor = Motor.new
  end



 def create
    @motor = Motor.new(motor_params)
    @motor.pecas.build(params[:id])
    respond_to do |format|
      if @motor.save
        format.html { redirect_to @motor, notice: 'Motor was successfully created.' }
        format.json { render action: 'show', status: :created, location: @motor }
      else
        format.html { render action: 'new' }
        format.json { render json: @motor.errors, status: :unprocessable_entity }
      end
    end
 end


private

    def set_motor
      @motor = Motor.find(params[:id])
    end

    def motor_params
      params.require(:motor).permit(:nome, {:peca_attributes => [:item]})
    end

Everything works fine (ALMOST). "Engine" has an attribute that is name:string and Peca has an attribute called item:string.

I am able to generate a record of pieces when I write an "engine" through the modified "engine" view but I cannot record the "item" attribute name of the "PECA" model".

It seems to me that it is a new STRONG PARAMETERS guideline in Rails 4. Can anyone help me?

Grateful!

2 answers

3

Include in new of my controller

def new
  @motor = Motor.new
  @motor.pecas.build   #  Linha incluída
end

In the object view motor, the object peca has to be pluralized.

<%= form_for(@motor) do |f| %>
      .
      .
      .
<%= f.fields_for :pecas do |peca_build| %>   #  'pecas' TEM QUE ESTAR NO PLURAL
    <div class="field">
      <p>
        <%= peca_build.label :item %>
        <%= peca_build.text_field :item %>
      </p>
    </div>
<% end %>

When defining parameters, pluralize the attribute:

def motor_params
  params.require(:motor).permit(:nome, {:pecas_attributes => [:item]})   #  'pecas' TEM 
end                                                               #QUE ESTAR NO PLURAL
  • Could you mark your answer as accepted?

-2

is missing put in params the id field

more or less like this:

def motor_params
   params.require(:motor).permit(:nome, pecas_attributes: [:id, :item])
end

and the new method is more or less like this:

def new
    @motor = Motor.new
    @motor.build_pecas
end

with this you can take the build from create

Browser other questions tagged

You are not signed in. Login or sign up in order to post.