Ruby on Rails - Creating a profile when user is created

不问归期 提交于 2019-12-04 18:08:01

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

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.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!