使用设计创建用户配置文件和用户的关联

时间:2014-03-03 20:59:39

标签: ruby-on-rails activerecord devise

我正在尝试创建一个user_profile模型以与Devise的用户模型一起使用

我有以下内容:

用户类

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_one :user_profile
  accepts_nested_attributes_for :user_profile

  after_create :build_profile

  private

  def build_profile
    user_profile.build_user_profile
  end

end

User_Profile Class

class UserProfile < ActiveRecord::Base

  belongs_to :user

  validates :username, presence: true
  validates :username, uniqueness: true, if: -> { self.username.present? }

  def build_user_profile

  end

end

我的观点(设计/注册/ new.html.erb)

<h2>Sign up</h2>

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

  <div><%= f.label :email %><br />
  <%= f.email_field :email, :autofocus => true %></div>

  <div><%= f.label :username %><br />
  <%= f.text_field :username, :autofocus => true %></div>

    <div><%= f.label :password %><br />
  <%= f.password_field :password %></div>

  <div><%= f.label :password_confirmation %><br />
  <%= f.password_field :password_confirmation %></div>

  <div><%= f.submit "Sign up" %></div>
<% end %>

<%= render "devise/shared/links" %>

当我打开页面时,出现以下错误:

  

未定义的方法`用户名'

我对协会很新 - 并且无法弄清楚原因:用户名不被识别(或者正确的方法是什么)。

我通过belongs_to :users, :user_profiles迁移在User(user_profiles_id)中添加了一个索引列。我还打算重写Devises注册控制器。

似乎无法获得这种加载形式。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

您应该将username包裹到fields_for块中:

<%= f.fields_for :user_profile do |profile_form| %>
  <div><%= profile_form.label :username %><br />
  <%= profile_form.text_field :username, :autofocus => true %></div>
<% end %>

它围绕f形式的特定模型创建范围。更多info here