【问题标题】:Rails Trying to create a profile after the user has been createdRails在创建用户后尝试创建配置文件
【发布时间】:2015-05-30 03:02:04
【问题描述】:

我正在尝试弄清楚如何为刚刚创建的用户创建新的个人资料,

我在 User 模型上使用设计,并且 User 模型与 UserProfile 模型具有一对一的关系。

这是我的用户模型的样子:

class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
  belongs_to :batch
  has_one :user_profile

  after_create :create_user_profile

  def create_user_profile
    self.user_profile.new(:name => 'username')
  end

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

这会产生以下错误:

nil:NilClass 的未定义方法 `new'

我已经在 rails c 中尝试过 User.find(1).user_profile 并且效果很好,所以我确信关系设置正确,

我可能是个大胖子,并试图错误地获取 self

另外,您能否告诉我如何访问模型中的参数...这可能吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord devise


    【解决方案1】:

    has_one 关系会自动添加:create_&lt;relationship&gt;build_&lt;relationship&gt; 方法。 Checkout the rails guide.

    你可以试试这个:

    after_create do
      create_user_profile(:name => 'username')
    end
    

    更有可能

    after_create do
      create_user_profile(:name => self.username)
    end
    

    【讨论】:

    • 谢谢约翰...这对我有用...你知道如何使用参数添加名称而不是输入静态值吗?我想在用户的新表单中添加用户名字段...可以吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 2012-07-14
    • 2020-08-03
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多