【问题标题】:undefined method `create' for nil:NilClass when trying to create profile in user model尝试在用户模型中创建配置文件时为 nil:NilClass 定义未定义的方法“create”
【发布时间】:2013-08-19 09:47:31
【问题描述】:

我搜索并找到了这个 Rails 3 undefined method `create' for nil:NilClass error while trying create a related object,但该解决方案也给出了错误 - 堆栈级别太深,因此在 SO 上询问它。

我有一个用户模型和配置文件模型,其中包含 belongs_to 和 has_one 关系。

在我的 user.rb 模型中,我有

after_create :create_profile

def create_profile
  self.profile.create
end

但这在 self.profile.create 行给出了“nil:NilClass 的未定义方法‘create’”。用户也没有被创建,也没有配置文件

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    after_create :create_profile就够了,不用定义create_profile方法,rails提供的。

    示例:

    class User < ActiveRecord::Base
      has_one      :profile
      after_create :create_profile
    end
    

    【讨论】:

    • 谢谢它的工作,还有一件事,用户 id 10 的个人资料 id 6 但他也可以查看和编辑其他个人资料,如 5,4 等,如何确保用户只能编辑属于他的个人资料?
    • 编辑 - 我使用了 @profile = current_user.profiles.find(params[:id]) 但这给出了未定义的方法配置文件错误
    • 会的。由于用户 has_one 个人资料,@profile = current_user.profile 可以工作。
    猜你喜欢
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-17
    • 2013-01-16
    • 1970-01-01
    相关资源
    最近更新 更多