params.require()。permit不能按预期工作

时间:2013-07-12 19:35:51

标签: ruby-on-rails ruby nested-forms nested-attributes

我有这个控制器

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

和这个观点

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

当我填写两个表单字段并点击“保存人员”时,我只收到{"name"=>"foo"} - 电话号码似乎消失了。

但是,当我将phones_attributes更改为phones时,我得到{"name"=>"foo", "phones"=>{"phone_number"=>"123"}}(但这会导致创建函数出现问题。

这里有什么问题?

请注意,此问题与该问题密切相关:accepts_nested_attributes_for: What am I doing wrong以及此帖:https://groups.google.com/forum/#!topic/rubyonrails-talk/4RF_CFChua0

2 个答案:

答案 0 :(得分:0)

您没有在控制器中定义@phones:

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

答案 1 :(得分:0)

终于找到了问题。在视图中应该有

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

而不是

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

@phron说已经在这里: accepts_nested_attributes_for: What am I doing wrong