Rails尝试在创建用户后创建配置文件 [英] Rails Trying to create a profile after the user has been created
问题描述
我正在试图找出刚刚创建的用户的新配置文件,
I'm trying to figure out how to create a new profile for the user that has just been created,
我在用户模型上使用devise, User模型与UserProfile模型有一对一的关系。
I'm using devise on the User model, and the User model has a one to one relationship with the UserProfile model.
以下是我的用户模型:
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
belongs_to :batch
has_one :user_profile
after_create :create_user_profile
def create_user_profile
self.user_profile.new(:name => 'username')
end
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
这会产生以下错误:
未定义的方法new为nil:NilClass
undefined method `new' for nil:NilClass
我尝试过 User.find (1).user_profile 在 rails c 中,所以我很确定关系的设置是否正确,
i've tried User.find(1).user_profile in rails c and that works so I'm pritty sure the relationship is setup correctly,
我'可能是一个大胖子noob,并试图获取自己不正确。
I'm probably being a big fat noob and trying to fetch self incorrectly.
加上你还可以告诉我如何访问params在模型...甚至可能?
plus can you also tell me how to access the params in a Model... is that even possible?
推荐答案
has_one关系将自动添加:create_<关系>
和 build_<关系>
方法。 检查导轨指南。
A has_one relationship will automatically add the :create_<relationship>
and build_<relationship>
methods. Checkout the rails guide.
您可以尝试这样:
after_create do
create_user_profile(:name => 'username')
end
或更有可能
after_create do
create_user_profile(:name => self.username)
end
这篇关于Rails尝试在创建用户后创建配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!