Rails有很多通过fields_for

时间:2018-05-06 19:49:01

标签: ruby-on-rails

我有一个我想要创建的表单,填充相应的模型表单,填充a的fields_for有很多表。

plan.rb 模型:

class Plan < ApplicationRecord
  has_many :plan_materials
  has_many :materials, through: :plan_materials
  accepts_nested_attributes_for :materials
end

materials.rb 模型:

class Material < ApplicationRecord
  has_many :plan_materials
  has_many :plans, through: :plan_materials
end

PlanMaterial 模型:

class PlanMaterial < ApplicationRecord
  belongs_to :plan
  belongs_to :material
end

这就是我在计划表格中所拥有的:

<%= form_for @plan do |form| %>
  <div class="form-group">
    <%= form.label :name %>
    <%= form.text_field :name, class: 'form-control' %>
  </div>

  <div class="form-group">
    <%= form.label :description %>
    <%= form.text_field :description, class: 'form-control' %>
  </div>

  <%= form.fields_for :materials, plan.materials.build do |material_fields| %>
    <%= material_fields.text_field :title %>
  <% end %>

  <%= form.submit %>
<% end %>

我之前创建了fields_for表单,但从未尝试在同一表单的新表中输入正在创建的表单的信息,以及他们正在选择的材料的ID。

我是通过plan.materials.build创建的,我发现这可能是错误的方法,因为我认为它不会在plan_materials表中构建它。

class PlansController < ApplicationController
  def index
    @plans = Plan.all
  end

  def new
    @plan = Plan.new
    @plan.materials.build
  end

  def create
    @plan = Plan.new(plan_params)

    respond_to do |format|
      if @plan.save
        format.html { redirect_to plan_path, notice: 'Plan has been created' }
      else
        format.html { render :new, notice: 'There was an error saving your plan' }
      end
    end
  end

  private

  def plan_params
    params.require(:plan).permit(:name, :description, :grade_id, :subject_id, :unit_id, materials_attributes: [:title])
  end
end

因此,回顾一下,我想创建一个计划,并能够为该计划添加材料。我需要在计划表中创建该计划,以及创建的计划的ID和在该表单中添加的材料的ID。我该怎么做呢?

0 个答案:

没有答案