0

我有这个控制器

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_attributesphonesI get时{"name"=>"foo", "phones"=>{"phone_number"=>"123"}}(但这会导致 create 函数出现问题。

这里有什么问题?

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

4

2 回答 2

0

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

 def new
    @person = Person.new
    @phones = @person.phones.new
 end
于 2013-07-12T19:51:35.067 回答
0

终于发现问题了。在视图中应该有

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

代替

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

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

于 2013-07-13T21:00:13.400 回答