本文介绍了params.require().permit不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个控制器

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

当我同时填写两个表单字段并单击"Save Person"时,我只会得到{"name"=>"foo"}-电话号码似乎消失了.

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

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

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.

这是怎么了?

请注意,该问题与以下问题密切相关: accepts_nested_attributes_for:我在做什么错了以及该帖子: https://groups.google.com/forum/#!topic/rubyonrails-talk/4RF_CFChua0

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

推荐答案

终于找到了问题所在.认为应该有

Finally found the problem. In the view there should be

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

代替

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

@phron在这里已经说过了: accepts_nested_attributes_for:我在做什么错

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

这篇关于params.require().permit不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 14:18