【发布时间】:2012-05-29 19:13:18
【问题描述】:
两个模型(步骤包含“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
以及新视图中的嵌套表单,其中带有用于语句的 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 %>
提交模型时不要保存,因为:“语句步骤不能为空”(步骤应在...之前创建)
【问题讨论】:
-
问题在于验证。我在语句模型中有这段代码:#validates validates :step_id, :presence => true with a belongs_to。所以我删除了验证,它正在工作。
-
请回答您的问题并接受您自己的答案,然后它不会显示为未解决。谢谢
-
请将其作为答案发布。
标签: ruby-on-rails-3 forms validation nested-forms nested-attributes