3

The two Models (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 the nested form in New view with form_fields for statements:

<%= 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 submit the models don't save because: "Statements step can't be blank" (step should be create before...)

user1364684
  • 800
  • 2
  • 8
  • 28

1 Answers1

0

You can use inverse_of to make this work while retaining the 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