views:

55

answers:

3

Hi,

I have the following code in my User model:

attr_protected :email

I'm trying to create a new user object, but I get a mass assignment protected error with the following code.

user = User.new(
    :first_name => signup.first_name,
    :last_name => signup.last_name,
    :email => signup.email,
    :birthday => signup.birthday,
    :encrypted_password => signup.encrypted_password,
    :salt => signup.salt
  )

Does anyone know how I can work around the attr_protected to get this code to work and assign a value to email?

Thank you.

+4  A: 
user = User.new(
  :first_name => signup.first_name,
  :last_name => signup.last_name,
  :birthday => signup.birthday,
  :encrypted_password => signup.encrypted_password,
  :salt => signup.salt
)
user.email = signup.email
Justice
+2  A: 

I literally just wrote a gem tonight to deal with this exact issue. I'm planning on adding it to RubyGems.org later this week after I give a presentation on it. Feel free to checkout the code in the mean time. http://github.com/beerlington/sudo_attributes

Using the gem, your code would change to:

user = User.sudo_new(
  :first_name => signup.first_name,
  :last_name => signup.last_name,
  :email => signup.email,
  :birthday => signup.birthday,
  :encrypted_password => signup.encrypted_password,
  :salt => signup.salt
)

You could also use sudo_create() if you want to save the instance

Beerlington
I love the idea :D
PeterWong