2

所以基本上我已经编写了自己的身份验证而不是使用 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。如果有人可以提供帮助,将不胜感激。

4

3 回答 3

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

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

然后,您的控制器将简化为:

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
于 2013-10-10T10:06:17.180 回答
13

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

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

after_create :create_profile

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

于 2014-11-06T12:39:08.563 回答
0

您在这里有两个错误:

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

第二行应该是:

@profile.user_id = @user.id

第一行创建配置文件,并且在分配user_id.

将这些行更改为:

@profile = Profile.create(user_id: @user.id)
于 2013-10-10T10:04:28.707 回答