Rails Trying to create a profile after the user ha

2019-09-20 03:46发布

问题:

I'm trying to figure out how to create a new profile for the user that has just been created,

I'm using devise on the User model, and the User model has a one to one relationship with the UserProfile model.

Here's what my User Model looks like:

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

This generate the following error:

undefined method `new' for nil:NilClass

i've tried User.find(1).user_profile in rails c and that works so I'm pritty sure the relationship is setup correctly,

I'm probably being a big fat noob and trying to fetch self incorrectly.

plus can you also tell me how to access the params in a Model... is that even possible?

回答1:

A has_one relationship will automatically add the :create_<relationship> and build_<relationship> methods. Checkout the rails guide.

You could try this:

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

Or more likely

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