Rails3:嵌套表单因为id而无法保存

时间:2012-05-23 08:49:43

标签: ruby-on-rails-3 forms validation nested-forms nested-attributes

两个模型(步骤包含“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

步骤控制器,方法new(使用@ step.statements.build)并创建:

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

和新视图中的嵌套表单,其中包含用于语句的form_fields:

<%= 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 %>

提交模型时不保存,因为:“语句步骤不能为空”(步骤应在之前创建...)

1 个答案:

答案 0 :(得分:0)

您可以使用inverse_of在保留验证的同时完成此工作:

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