问题
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
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.
回答1:
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
This will now always create a profile for a newly created user.
Your controller then gets simplified to:
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
回答2:
This is now much easier in Rails 4.
You only need to add the following line to your user model:
after_create :create_profile
And watch how rails automagically creates a profile for the user.
回答3:
You have two errors here:
@profile = Profile.create
profile.user_id = @user.id
The second line should be:
@profile.user_id = @user.id
The first line creates the profile and your are not 're-saving' after the assignment of the user_id
.
Change these lines to this:
@profile = Profile.create(user_id: @user.id)
来源:https://stackoverflow.com/questions/19292645/ruby-on-rails-creating-a-profile-when-user-is-created