为嵌套实体设计注册

Devise registration for with nested entity

我正在构建一个 Rails 应用程序,用户可以在其中拥有更多地址。

User has_many :addresses
Address belong_to :user

我正在使用 Devise 进行身份验证。我希望在用户注册时通过一个表单创建一个用户实体和第一个地址实体。

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= f.email_field :email %><br />
  <%= t.password_field :password %><br />

  <%= f.fields_for resource.addresses do |a| %>
    <%= a.text_field :street %>
  <% end %>
<% end %>

但我得到了

未定义方法 'street' ActiveRecord::Associations::CollectionProxy []

必须在控制器中做什么?

谢谢

编辑

我已经在用户模型中:

accepts_nested_attributes_for :addresses

并且我已经像这样更新了我的控制器:

class Users::RegistrationsController < Devise::RegistrationsController

  # GET /resource/sign_up
  def new
    # super
    build_resource({})
    yield resource if block_given?
    resource.addresses.build
    respond_with resource
  end
end

并查看:

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= f.email_field :email %><br />
  <%= t.password_field :password %><br />

  <%= f.fields_for resource.addresses.first do |a| %>
  <%= a.text_field :street %>
<% end %>

所以表格正在显示。但是当我 post 时, resource.addresses.first 仍然是 null:

nil:NilClass

的未定义方法“model_name”

谢谢

您需要添加 accepts_nested_attributes_for 个地址

Class User < ActiveRecord::Base
  has_many :addresses
  accepts_nested_attributes_for :addresses
end

您还需要初始化地址对象,您可以在控制器级别(最佳方法)或在视图中执行此操作

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= f.email_field :email %><br />
  <%= t.password_field :password %><br />
  <% resource.addresses.build %>
  <%= f.fields_for resource.addresses do |a| %>
    <%= a.text_field :street %>
  <% end %>
<% end %>

并且您需要添加与您在控制器上接收到的参数相对应的内容。