所以基本上我已经编写了自己的身份验证而不是使用 gem,因此我可以访问控制器。我的用户创建工作正常,但是当创建我的用户时,我还想在我的个人资料模型中为他们创建个人资料记录。我已经让它大部分工作了,我只是似乎无法将新用户的 ID 传递到新的 profile.user_id 中。这是我在用户模型中创建用户的代码。
def create
@user = User.new(user_params)
if @user.save
@profile = Profile.create
profile.user_id = @user.id
redirect_to root_url, :notice => "You have succesfully signed up!"
else
render "new"
end
配置文件正在创建,它只是不添加新创建的用户的 user_id 。如果有人可以提供帮助,我们将不胜感激。
您确实应该将其作为用户模型中的回调来执行:
User
after_create :build_profile
def build_profile
Profile.create(user: self) # Associations must be defined correctly for this syntax, avoids using ID's directly.
end
end
现在,这将始终为新创建的用户创建配置文件。
然后你的控制器会被简化为:
def create
@user = User.new(user_params)
if @user.save
redirect_to root_url, :notice => "You have succesfully signed up!"
else
render "new"
end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)