marc
marc

Reputation: 11

Mass assignment problem when instantiating a model

I have a User model (Devise) and have created a Profile model with has_one / belongs_to relationship. I'm trying to automatically create a profile when the User is created as follows :

class User < ActiveRecord::Base   
   has_many :videos, :dependent => :destroy
   has_one :profile, :dependent => :destroy

    after_create :create_profile

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

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me

  protected

  def create_profile
    Profile.create :user_id => self.id
  end

end

The profile gets created but the user id does not get populated. I get a Mass Assignment warning with regard to setting :user_id on the profile because I have attr_accessible exposing a few fields on the Profile.

I dont want to remove the attr_accessible but dont understand why setting one field is considered mass assignment. I figured this might be to do with passing a hash so Ive tried the following as a workaround :

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

This removes the warning but the user_id is still not getting set on the profile. What is the correct way to go about solving this ?

Any clarity much appreciated ! :)

Upvotes: 0

Views: 193

Answers (1)

bender
bender

Reputation: 1428

Are you calling @profile.save at the end of your workaround?

Maybe you can try this:

def create_profile
  self.build_profile.save
end

Upvotes: 1

Related Questions