【问题标题】:Ruby on Rails - Creating a profile when user is createdRuby on Rails - 创建用户时创建配置文件
【发布时间】:2013-10-10 09:57:08
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails model controller profile


    【解决方案1】:

    您确实应该将其作为用户模型中的回调来执行:

    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 控制器吗?
    【解决方案2】:

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

    您只需在您的用户模型中添加以下行:

    after_create :create_profile
    

    并观察 rails 如何自动为用户创建个人资料。

    【讨论】:

      【解决方案3】:

      这里有两个错误:

      @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
      猜你喜欢
      • 2016-04-20
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 1970-01-01
      相关资源
      最近更新 更多