设计用户的个人资料模型?

Tro*_*nic 35 authentication ruby-on-rails devise

我想扩展我的设计安装的注册表单.我创建了一个Profile模型,现在问自己,如何将表单的特定数据添加到此模型中.UserController设计在哪里?

提前致谢!

mbr*_*ing 45

假设您有一个带有has_oneProfile关联的User模型,您只需要在User中允许嵌套属性并修改您的设计注册视图.

运行该rails generate devise:views命令,然后registrations#new.html.erb使用fields_for表单帮助程序修改设计视图,如下所示,使您的注册表单更新您的配置文件模型以及您的用户模型.

<div class="register">
  <h1>Sign up</h1>

  <% resource.build_profile %>
  <%= form_for(resource, :as => resource_name,
                         :url => registration_path(resource_name)) do |f| %>
    <%= devise_error_messages! %>

    <h2><%= f.label :email %></h2>
    <p><%= f.text_field :email %></p>

    <h2><%= f.label :password %></h2>
    <p><%= f.password_field :password %></p>

    <h2><%= f.label :password_confirmation %></h2>
    <p><%= f.password_field :password_confirmation %></p>

    <%= f.fields_for :profile do |profile_form| %>
      <h2><%= profile_form.label :first_name %></h2>
      <p><%= profile_form.text_field :first_name %></p>

      <h2><%= profile_form.label :last_name %></h2>
      <p><%= profile_form.text_field :last_name %></p>
    <% end %>

    <p><%= f.submit "Sign up" %></p>

    <br/>
    <%= render :partial => "devise/shared/links" %>
  <% end %>
</div>
Run Code Online (Sandbox Code Playgroud)

在您的用户模型中:

class User < ActiveRecord::Base
  ...
  attr_accessible :email, :password, :password_confirmation, :remember_me, :profile_attributes
  has_one :profile
  accepts_nested_attributes_for :profile
  ...
end
Run Code Online (Sandbox Code Playgroud)

  • 要完成此答案,请不要忘记添加您的用户模型:attr_accessible:profile_attributes和accepts_nested_attributes_for:profile(在此处信用:http://railsforum.com/viewtopic.php?id = 42817) (9认同)
  • 实际上它应该是<%resource.profile || resource.build_profile%>,否则您将无法在表单失败时获取传递的值. (7认同)
  • 非常简单的解决方案,谢谢!只是一点点考虑:你不觉得在视图中构建配置文件有点脏吗?这只是因为我们不能轻易编辑Devise叹气控制器或者我可能太挑剔了?:-) (3认同)
  • 不,你不是太挑剔.:)我同意你的意见,通常你会在控制器中创建一个新的模型实例,而不是在视图中.但正如您所提到的,因为需要更新Devise控制器,在这种特殊情况下最简单和最简单的解决方案是在视图中执行此操作. (2认同)

ksi*_*elo 8

为了补充mbreining的答案,在Rails 4.x中,您需要使用强参数来存储嵌套属性.创建注册控制器子类:

RegistrationsController < Devise::RegistrationsController

  def sign_up_params
    devise_parameter_sanitizer.sanitize(:sign_up)
    params.require(:user).permit(:email, :password, profile_attributes: [:first_name, :last_name])
  end
end
Run Code Online (Sandbox Code Playgroud)