[英]Using devise with nested form on sign_up
表格未显示Pessoa的字段,怎么了?
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<h4>Usuário</h4>
<%= f.email_field :email, autofocus: true %>
<% if @minimum_password_length %>
<em>(<%= @minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "off" %>
<%= f.password_field :password_confirmation, autocomplete: "off" %>
<h4>Pessoa</h4>
<%= f.fields_for :pessoa do |p| %>
<%= p.text_field :nome %>
<% end %>
<div class="actions">
<%= f.submit "Cadastrar" %>
</div>
<% end %>
我只看到电子邮件,密码和密码确认...类用户:
class Usuario < ActiveRecord::Base
has_one :pessoa
has_many :pedidos, through: :pessoa
accepts_nested_attributes_for :pessoa
和RegistrationController:
class Usuarios::RegistrationsController < Devise::RegistrationsController
def new
build_resource(sign_up_params)
self.resource.pessoa = Pessoa.new
respond_with self.resource
end
def create
super
end
private
def sign_up_params
params.require(:user).permit(pessoas_attributes: [:nome])
end
end
佩索阿属于乌苏里奥,好吗? 并需要显示电子邮件,密码,密码确认和名称。 提交时需要将两个值(Usuarios和Pessoas)保存在已注册的值中。 我错了吗? 谢谢!
编辑
Pessoa显示的是表格,但是我填写完数据后,不保存在DB中,为什么? 我做了我被要求做的事情。 用户值保存正常,但比索不保存。
在你的控制器sign_up_params
从改变pessoas_attributes
到pessoa_attributes
,因为你有一个has_one
在你的模型关系。
同样在sign_up_params
方法中,您需要更改您的params键,您拥有:user
但似乎是:usuario
另外:您可以将以下方法添加到用户模型:
def with_pessoa
self.pessoa = Pessoa.new
self
end
并修改视图:
...
<% form_for [resource_name, resource.with_pessoa], :url => registration_path(resource_name) do |f| %>
...
<% f.fields_for :pessoa do |pessoa_form| %>
...
<% end %>
这样,您将拥有嵌套表单,可以向用户添加一个比索。 要向用户动态添加多个比索 ,请查看Ryan Bates撰写的Railcast#197 。 确保将资源对作为数组传递,否则将收到如下错误:“参数数量错误(3表示2)”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.