所以基本上我已经编写了自己的身份验证而不是使用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。如果有人能提供帮助,我们将不胜感激。
答案 0 :(得分:12)
您应该在用户模型中执行此回调:
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
答案 1 :(得分:11)
现在在Rails 4中更容易了。
您只需将以下行添加到您的用户模型中:
after_create :create_profile
观看rails如何自动为用户创建配置文件。
答案 2 :(得分:0)
这里有两个错误:
@profile = Profile.create
profile.user_id = @user.id
第二行应该是:
@profile.user_id = @user.id
第一行创建了个人资料,并且在分配user_id
后您没有“重新保存”。
将这些行更改为:
@profile = Profile.create(user_id: @user.id)