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

时间:2010-11-29 20:23:20

标签: ruby-on-rails authentication devise

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

提前致谢!

5 个答案:

答案 0 :(得分:45)

假设您的用户模型具有has_one个人资料关联,您只需在用户中允许嵌套属性并修改您的设计注册视图。

运行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>

在您的用户模型中:

class User < ActiveRecord::Base
  ...
  attr_accessible :email, :password, :password_confirmation, :remember_me, :profile_attributes
  has_one :profile
  accepts_nested_attributes_for :profile
  ...
end

答案 1 :(得分:8)

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

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

答案 2 :(得分:4)

你的问题不是很清楚,但我假设你的Devise模型是User,你创建了属于用户的另一个模型Profile

您需要使用rails g controller users为您的用户模型创建一个控制器。

您还需要使用rails generate devise:views 为您的用户生成观看次数,以便用户在创建帐户时可以添加个人资料信息。

从那里,它就像任何其他模型一样:创建用户和配置文件实例并链接这两者。然后,在控制器中,使用current_user.profile访问当前用户的个人资料。

请注意,如果您要以这种方式管理用户,则需要从:registerable模型中删除User模块(同时阅读https://github.com/plataformatec/devise/wiki/How-To:-Manage-users-through-a-CRUD-interface

答案 3 :(得分:2)

为了不在视图中放置构建资源,另一种方法是重写设计控制器,确切地说,新方法,你需要做的就是将它改为:

 def new
   build_resource({})
   resource.build_profile 
   respond_with self.resource
 end

答案 4 :(得分:2)

我建议Creating Profile for Devise users查看同一问题的最新答案并使用Rails 4 + Devise

相关问题