Ruby on Rails - 创建用户时创建配置文件 [英] Ruby on Rails - Creating a profile when user is created

查看:145
本文介绍了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

这篇关于Ruby on Rails - 创建用户时创建配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆