Rails3: nested form not saved since id

Two models (the step contains "accepts_nested_attributes_for"):

class Step < ActiveRecord::Base

  has_many :statements  
  accepts_nested_attributes_for :statements

end


class Statement < ActiveRecord::Base

  belongs_to :step

end

Step Controller, methods new (with @ step.statements.build) and create:

def new
    @step = Step.new
    @step.statements.build

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @step }
    end
  end

def create
        @step = Step.new(params[:step])

        respond_to do |format|
          if @step.save
            format.html { redirect_to @step, notice: 'Step was successfully created.' }
            format.json { render json: @step, status: :created, location: @step }
          else
            format.html { render action: "new" }
            format.json { render json: @step.errors, status: :unprocessable_entity }
          end
        end
      end

and a nested form in a new view using form_fields for operators:

<%= form_for(@step) do |step_form| %>

   <div class="field">
    <%= step_form.label :step_type %><br />
    <%= select("step", "step_type_id", @step_types.collect {|p| [ p.name, p.id ] }, {:include_blank => true}) %>
  </div>

  <%= step_form.fields_for :statements do |statement_form| %>

  <div class="field">
    <%= statement_form.label :title %><br />
    <%= statement_form.text_field :title %>
  </div>

  <% end %>

  <div class="actions">
    <%= step_form.submit %>
  </div>
<% end %>

when sending the models are not saved, because: "The step of the instructions cannot be empty" (the step must be created before ...)

+3
source share
1 answer

You can use inverse_of to do this work while maintaining validation:

class Step < ActiveRecord::Base
  has_many :statements, inverse_of: :step
  accepts_nested_attributes_for :statements
end

class Statement < ActiveRecord::Base
  belongs_to :step, inverse_of: :statements
  validates :step, presence: true
end
0
source

All Articles