嵌套表单属性

时间:2015-06-08 19:34:26

标签: ruby-on-rails nested-forms

我有一个表单正在保存在数据库中,但我想保存一些将保存在不同记录中的字段。

<%= form_for @complaint, url: {action: 'create'}, :html => {:multipart => true} do |f| %>
  <%= f.text_field :complaint_info %>
  <%= f.fields_for :witness do |witnesses_form| %>
    <%= witnesses_form.text_field :name %>
  <% end %>
<% end %>

在我的控制器中:

  def new
    @complaint = Complaint.new
  end

  def create
    @complaint = current_user.complaints.build(complaint_params)
    if @complaint.save

      redirect_to dashboard_complaint_path(@complaint)
    else
      render 'new'
    end
  end

  private

  def complaint_params
    params.require(:complaint).permit(:complaint_info, witnesses_attributes: [:name])
  end

在模型上:

class Complaint < ActiveRecord::Base
  belongs_to :user
  has_many   :witnesses
  accepts_nested_attributes_for :witnesses
end

class Witness < ActiveRecord::Base
  belongs_to :complaint
end

但是我收到了这个错误:

Unpermitted parameter: witness

一切似乎都是假设的,我在这里缺少什么?

编辑:

能够通过添加以下内容来保存记录:

@complaint.witnesses.build

到控制器中的create操作,但仍然没有让我保存:name那里

<ActiveRecord::Relation [#<Witness id: 1, name: nil, phone: nil, complaint_id: 8, created_at: "2015-06-08 20:05:06", updated_at: "2015-06-08 

编辑2:

能够通过将@complaint.witnesses.buildcreate操作移动到new操作来修复它并修复它,现在我可以创建记录并让我保存text_fields它

2 个答案:

答案 0 :(得分:0)

您可以尝试更改控制器和视图代码,如下所示

在控制器中

 def new
   @complaint = Complaint.new
   @witnesses = @complaint.witnesses.build
 end

 def edit
   @witnesses = @complaint.witnesses
 end

在视图中

  <%= f.fields_for :witnesses, @witnesses do |witnesses_form| %>
     <%= witnesses_form.text_field :name %>
  <% end %>

答案 1 :(得分:0)

我可以通过将@complaint.witnesses.build添加到new操作而不是create操作来解决此问题。

所以我的控制器现在看起来像这样:

  def new
    @complaint = Complaint.new
    @complaint.witnesses.build
  end

  def create
    @complaint = current_user.complaints.build(complaint_params)
    if @complaint.save

      redirect_to dashboard_complaint_path(@complaint)
    else
      render 'new'
    end
  end

  private

  def complaint_params
    params.require(:complaint).permit(:complaint_info, witnesses_attributes: [:name])
  end
相关问题