Rails 4嵌套表单Simple_form_for& simple_field_for

时间:2014-11-10 02:28:23

标签: ruby-on-rails ruby simple-form

我只是想生成一个简单的嵌套表单,如下所示:

<%= simple_form_for @profile do |f| %>
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= f.input :phone_number %>
<%= f.simple_fields_for :addresses do |p| %>
  <%= p.input :street %>
  <%= p.input :city %>
  <%= p.input :state, collection: us_states %>
  <%= p.input :zip_code %>
<% end %>
<%= f.button :submit %>

我的模特:

class Profile < ActiveRecord::Base
  belongs_to :customer
  has_many :addresses
  accepts_nested_attributes_for :addresses
end

class Address < ActiveRecord::Base
  belongs_to :profile
end

我的控制器:

class ProfilesController < ApplicationController
  before_action :authenticate_customer!

  def new
    @profile = Profile.new
  end
end

不幸的是,嵌套属性addresses没有填充页面上的任何内容,我希望看到streetcity等字段,但我什么也得不到。

但是,如果我将<%= f.simple_fields_for :addresses do |p| %>更改为<%= f.simple_fields_for :address do |p| %>,则字段会正确显示。

不幸的是,这样做会导致问题,因为我无法使用文档中概述的accepts_nested_attributes_for帮助程序(据我所知)。知道为什么这不起作用吗?

2 个答案:

答案 0 :(得分:2)

原因是嵌套表单需要创建的对象才能工作。它看起来像是实例化的,但地址却没有。

class ProfilesController < ApplicationController
  before_action :authenticate_customer!

  def new
   @profile = Profile.new
   @profile.addresses.create   # this will create the address object that the nested form will use
  end
end

我认为你还需要创建一个Profile而不是创建它的实例。

@profile = Profile.create

我自己一直在使用嵌套表单,这就是它对我有用的方式。

答案 1 :(得分:1)

解决方案是在#new操作中构建配置文件和地址,以使其正常工作。修改后的工作代码:

class ProfilesController < ApplicationController
  before_action :authenticate_customer!

  def new
    @profile = current_customer.build_profile
    @profile.addresses.build
  end
end

你需要看看你的参数是如何通过的,但是因为我有一个has_many,所以他们通过一个记录id的密钥进行了哈希处理。