Nested form attributes

44 views Asked by At

I have one form working to save in the database but I want to save some fields that are going to be saved in a different record.

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

In my controller:

  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

on the model:

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

.

class Witness < ActiveRecord::Base
  belongs_to :complaint
end

But I'm getting this error:

Unpermitted parameter: witness

Everything seems to be as it suppose to be, what am I missing here?

EDIT:

was able to save the record by adding:

@complaint.witnesses.build

to the create action in the controller but it is still not letting me save the :name there

<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 

EDIT 2:

Was able to fix it by moving the @complaint.witnesses.build from the create action to the new action and it fixed it, now I can create the record and lets me save the text_fields in it.

2

There are 2 answers

3
Rokibul Hasan On

Can you try with changing your controller and views codes as following

In controller

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

 def edit
   @witnesses = @complaint.witnesses
 end

In views

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

I was able to fix it by adding @complaint.witnesses.build to the newaction instead of the create action.

So my controller now looks like this:

  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