3

两个模型(步骤包含“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.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 for statements 的 New 视图中的嵌套表单:

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

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

4

1 回答 1

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
于 2015-08-23T15:48:29.987 回答