簡體   English   中英

在sign_up上將devise與嵌套表單一起使用

[英]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_attributespessoa_attributes ,因為你有一個has_one在你的模型關系。

同樣在sign_up_params方法中,您需要更改您的params鍵,您擁有:user但似乎是:usuario

另外:您可以將以下方法添加到用戶模型:

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 %>

這樣,您將擁有嵌套表單,可以向用戶添加一個比索。 要向用戶動態添加多個比索 ,請查看Ryan Bates撰寫的Railcast#197 確保將資源對作為數組傳遞,否則將收到如下錯誤:“參數數量錯誤(3表示2)”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM