ruby-on-rails-3 - Rails3 : Nested form doesn't save because id

标签 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

Step Controller,新方法(使用@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

以及在新 View 中使用 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 %>

提交模型时不保存,因为:“Statements step can't be blank”(step should be create before...)

最佳答案

您可以在保留验证的同时使用 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

关于ruby-on-rails-3 - Rails3 : Nested form doesn't save because id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10716547/

相关文章:

php - Symfony 2 Forms实体字段类型分组

c# - 必需如果不在 MVC 5 中工作?

ruby - 为什么使用 Rails public_method?

javascript - 如何在 View 中将变量从 Controller 传递到 JavaScript?

php - Symfony2,如何使表单标签类/属性与​​其输入不同?

javascript - 为什么我会收到一封空电子邮件?

javascript - jQuery 确保填写所有表单字段

javascript - 二月份的表单验证

Facebooker 和 Rails3 与 OpenGraph

ruby - 在 ruby 中以秒为单位转换时间