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

不问归期 提交于 2019-12-13 08:14:18

问题


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



来源:https://stackoverflow.com/questions/17622741/params-require-permit-does-not-work-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!