0

我有一个用户模型(设计)并创建了一个具有 has_one / belongs_to 关系的 Profile 模型。我正在尝试在创建用户时自动创建配置文件,如下所示:

class User < ActiveRecord::Base   
   has_many :videos, :dependent => :destroy
   has_one :profile, :dependent => :destroy

    after_create :create_profile

  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me

  protected

  def create_profile
    Profile.create :user_id => self.id
  end

end

配置文件已创建,但未填充用户 ID。我收到关于在个人资料上设置 :user_id 的批量分配警告,因为我有 attr_accessible 公开个人资料上的一些字段。

我不想删除 attr_accessible 但不明白为什么设置一个字段被视为批量分配。我认为这可能与传递哈希有关,因此我尝试了以下解决方法:

@profile = Profile.create
@profile.user_id = self.id

这将删除警告,但 user_id 仍未在配置文件中设置。解决这个问题的正确方法是什么?

任何清晰度都非常感谢!:)

4

1 回答 1

1

您是否在解决方法结束时调用@profile.save?

也许你可以试试这个:

def create_profile
  self.build_profile.save
end
于 2011-07-29T16:51:52.487 回答