Search code examples
ruby-on-railsnested-forms

getting error while using nested form in rails


I am using nested form in rails , parameters are coming in console but not save into the database table

error : Unpermitted parameter: shyain_rekis

Is there mistake in aru_params ? If there then, what is the mistake?

def aru_params
  params.require(:aru).permit(:shyain_rekis_attributes => [:id, :emp_type, :company_leaving_reason, :_destroy])
end

view :

<%= f.fields_for :shyain_rekis_attributes do |ff| %>
    <tr>
        <td><%= ff.select :emp_type,TShyainTouyouJoshinsho::EMP_TYPE,{}, class: 'form-control' , :disabled => @disabled_field %></td>
        <td><%= ff.text_field :company_leaving_reason, class: 'form-control' , :disabled => @disabled_field %></td>
        <td><%= f.hidden_field :_destroy %>
            <%= link_to '削除' ,'#' , class: " btn btn-xs btn-danger remove_record" %>
        </td>
    </tr>
<% end %>  
Parameters: {"shyain_rekis_attributes"=>{"1555403656594"=> {"shyain_rekis"=>{"emp_type"=>"abc",company_leaving_reason"=>""}, "_destroy"=>"false"}}

I want to resolve error and save data into database table of nested form


Solution

  • (You may already have done that, but) To achieve what you want, instantiate the variable in the controller like so:

    def new
      @aru = Aru.new
    # other stuff...
    def edit
      @aru = Aru.find(params[:id])
    

    Then you have to pass an instance to the parent form tag, so if you have a symbol as the parameter switch it to the instance, something like this:

    <%= form_for @aru do |f| %>
    

    For your nested form you don't need to use _attributes as the fields_for argument

    <%= f.fields_for :shyain_rekis do |ff| %>
        <tr>
            <td><%= ff.select :emp_type,TShyainTouyouJoshinsho::EMP_TYPE,{}, class: 'form-control' , :disabled => @disabled_field %></td>
            <td><%= ff.text_field :company_leaving_reason, class: 'form-control' , :disabled => @disabled_field %></td>
            <td>
                <%= ff.hidden_field :_destroy %>
                <%= link_to '削除' ,'#' , class: " btn btn-xs btn-danger remove_record" %>
            </td>
        </tr>
    <% end %>  
    

    Don't forget to scope the _destroy hidden field to your nested form, or it will not destroy the related object.