Ruby on Rails - 在创建用户时创建配置文件

Luk*_*ard 2 profile controller model ruby-on-rails

所以基本上我已经编写了自己的身份验证而不是使用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
Run Code Online (Sandbox Code Playgroud)

配置文件创建它只是不添加新创建的用户的user_id.如果有人可以提供帮助,将不胜感激.

Mat*_*att 13

你应该在用户模型中作为回调执行此操作:

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
Run Code Online (Sandbox Code Playgroud)

现在,它将始终为新创建的用户创建配置文件.

然后您的控制器被简化为:

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
Run Code Online (Sandbox Code Playgroud)


kar*_*gen 12

这在Rails 4中现在要容易得多.

您只需将以下行添加到用户模型:

after_create :create_profile
Run Code Online (Sandbox Code Playgroud)

并观察rails如何自动为用户创建配置文件.