【问题标题】:Using devise with nested form on sign_up在 sign_up 上使用带有嵌套形式的设计
【发布时间】:2016-02-17 22:06:30
【问题描述】:

表单没有显示 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

和注册控制器:

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

Pessoa 属于 Usuario,好吗?并需要显示电子邮件、密码、密码确认和姓名。提交时需要将注册的值保存在两个表(Usuarios 和 Pessoas)中。我错了什么?谢谢!

编辑

Pessoa 显示的表格,但是我填完数据后,没有保存到DB,为什么?我做了我被要求做的事情。用户值保存正常,但比索不保存。

【问题讨论】:

  • 检查您的sign_up_params 方法。 pessoas_attributes 应该是 pessoa_attributes,因为它是 has_one 而不是 has_many。提交表单时还要检查 params 键,可能是usuario
  • 如果你的控制器真的被调用了,还要检查 Rails 服务器日志 - 如果不是,你错过了自定义设计路线或没有正确完成。您也可以通过运行rake routes 来检查它

标签: ruby-on-rails ruby-on-rails-4 devise nested-forms nested-form-for


【解决方案1】:

在您的控制器中,sign_up_paramspessoas_attributes 更改为 pessoa_attributes,因为您的模型中有 has_one 关系。

同样在sign_up_params 方法中你需要更改你的参数键,你有:user 但它似乎是:usuario

另外:您可以在 User 模型中添加以下方法:

user.rb

def with_pessoa
  self.pessoa = Pessoa.new
  self
end

并修改视图:

new.html.erb

...
<% form_for [resource_name, resource.with_pessoa], :url => registration_path(resource_name) do |f| %>
...
  <% f.fields_for :pessoa do |pessoa_form| %>
  ...
  <% end %>

这样,您将拥有一个嵌套表单来向用户添加一个比索。要为用户动态添加多个比索,请检查Railcast #197 by Ryan Bates。确保您将这对资源作为数组传递,否则您将收到如下错误:“参数数量错误(3 为 2)”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多