Ruby on Rails - 创建用户时创建配置文件
所以基本上我写了我自己的身份验证,而不是使用gem,所以我可以访问控制器。我的用户创建工作正常,但是当我的用户创建我还要在我的配置文件模型中为他们创建一个配置文件记录。我有它的大部分工作,我只是不能似乎将ID从新用户传递到新的profile.user_id。这是我的用户创建在我的用户模型中的代码。
So basically I have wrote my own authentication instead of using a gem so I have access to the controllers. My user creation works fine but when my users are created I want to also create a profile record for them in my profile model. I have got it mostly working I just cant seem to pass the ID from the new user into the the new profile.user_id. Here is my code for the user creation in my user model.
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。
The profile is creating it is just not adding a user_id from the newly created user. If anyone could help it would be appreciated.
你应该真的这样做在用户模型中的回调:
You should really do this as a callback in the user model:
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