params.require().permit does not work as expected

2019-09-06 21:22发布

问题:

I have this controller

class PeopleController < ApplicationController
    def new
        @person = Person.new
        @person.phones.new
    end

    # this is the action that gets called by the form
    def create
        render text: person_params.inspect
#       @person = Person.new(person_params)
#       @person.save

#       redirect_to people_path
    end

    def index
        @person = Person.all
    end

private

    def person_params
        params.require(:person).permit(:name, phones_attributes: [ :id, :phone_number ])
    end

end

and this view

<%= form_for :person, url: people_path do |f| %>
  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>

  <%= f.fields_for :phones do |f_phone| %>
    <div class="field">
      <p>
        <%= f_phone.label :phone_number %><br />
        <%= f_phone.text_field :phone_number %>
      </p>
    </div>
    <% end %>

  <p>
    <%= f.submit %>
  </p>
<% end %>

When I fill out both form fields and hit "Save Person" I only get {"name"=>"foo"} - the phone number seems to vanish.

However, when I change phones_attributes to phones I get {"name"=>"foo", "phones"=>{"phone_number"=>"123"}} (this would however cause problems with the create function.

What's wrong here?

Please note that this question is strongly related to that one: accepts_nested_attributes_for: What am I doing wrong as well as to this posting: https://groups.google.com/forum/#!topic/rubyonrails-talk/4RF_CFChua0

回答1:

You don't have @phones defined in the controller:

 def new
    @person = Person.new
    @phones = @person.phones.new
 end


回答2:

Finally found the problem. In the view there should be

<%= form_for @person, url: people_path do |f| %>

Instead of

<%= form_for :person, url: people_path do |f| %>

@phron said that already here: accepts_nested_attributes_for: What am I doing wrong