Ruby on Rails - 当用户创建时创建个人资料

3

基本上,我编写了自己的身份验证,而不是使用宝石(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

该配置文件的创建并未将新创建用户的user_id添加进去。如有任何人能提供帮助,将不胜感激。

3个回答

14

你应该在用户模型中使用回调函数来完成这个操作:

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

好主意。我认为你的建议是_User has_one Profile_。对吗?我需要创建一个Profile控制器吗? - Arup Rakshit

14

这在Rails 4中现在变得更加容易。

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

after_create :create_profile

看看Rails如何自动为用户创建个人资料。


0

你这里有两个错误:

@profile = Profile.create
profile.user_id = @user.id

第二行应该是:
@profile.user_id = @user.id

第一行创建了个人资料,分配了user_id后没有进行“重新保存”。

将这些行更改为:

@profile = Profile.create(user_id: @user.id)

我可以像 profile.email = user.email 一样向个人资料添加附加字段吗? - Md Kauser Ahmmed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接