mercredi 17 février 2016

Multiple non-nested model creation on same page with Rails 4

I'm using this good answer:

http://ift.tt/1LtCDob

in my project:

_form.html.erb:

= form_tag({controller: "users", action: "create"}, remote: true) do
  %table
    %tr
      %td= text_field_tag 'user[][first_name]'
      %td= text_field_tag 'user[][last_name]'

    %tr.actions
      %td= submit_tag 'Save'
      %td= button_tag 'Add new user form', id: 'add_user_form'

    %tr.new_user_row.hidden # hidden class matches the css rule: {display:none;}
      %td= text_field_tag "user[][first_name]"
      %td= text_field_tag "user[][last_name]"

:javascript # jQuery
  $('#add_user_form').bind('click', function(e) {
    var row = $('tr.new_user_row').clone().removeClass('hidden new_user_row');
    $('tr.actions').before(row); # will append the <tr> before the actions
  });

and UsersController:

def create
  params[:user].each do |attr|
    User.create(attr)
  end
end

but when I submit it give me this error:

ActiveModel::ForbiddenAttributesError

If I disable Rails 4 strong_parameters by config.action_controller.permit_all_parameters = true in config/application.rb it works and save.

How to permit the hash

..., "user"=>[{"first_name"=>"Name", "last_name"=>"Last"}, {"first_name"=>"", "last_name"=>""}],....

in my controller?

Aucun commentaire:

Enregistrer un commentaire