accepts_nested_attributes_for in Rails 4

0

Expensive!

I'm having a hard time because I'm new to Rails.

I'm trying to generate a form with two templates through Nested Form Rails. It's a simple template.

"Engine" has one or more "parts", and "part" has only one "motor". 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 perfectly (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 parts when I record a "engine" through the modified "engine" view but I CAN NOT RECORD THE NAME OF THE "ITEM" ATTRIBUTE NAME OF THE "PECA" MODEL.

I think it's a new STRONG PARAMETERS guideline in rails 4. Can anyone help me?

Thank you!

    
asked by anonymous 11.06.2014 / 21:44

2 answers

3

Include in% of my controller%

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

In the view of the object new , the object motor 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 %>

In the parameter definition, pluralize peca :

def motor_params
  params.require(:motor).permit(:nome, {:pecas_attributes => [:item]})   #  'pecas' TEM 
end                                                               #QUE ESTAR NO PLURAL
    
12.06.2014 / 16:19
-2

The id field is missing in the params

getting more or less like this:

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

and in the new method it looks more or less like this:

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

This can take the build from create

    
08.07.2017 / 00:26