I am trying to lowercase params[:user][:email] in my application but currently I'm using @user = User.new(params[:user]) (which includes the email) in my def create. Is it possible to allow for mass assignment for everything except for a single item?
I know I could just not use mass assignment but I was wondering if this was possible.
Yes.
class User
attr_protected :email
end
Here's how you'd use it:
user = User.new(params[:user])
user.email = params[:user][:email].downcase
If you want to downcase the email attribute automatically though, you can simply override the email= method, which I strongly recommend:
class User < ActiveRecord::Base
def email=(other)
write_attribute(:email, other.try(:downcase))
end
end
Loading development environment (Rails 3.2.5)
irb(main):001:0> User.new({:email => '[email protected]'})
=> #<User id: nil, email: "[email protected]", username: nil, created_at: nil, updated_at: nil>
irb(main):002:0> User.new({:email => nil})
=> #<User id: nil, email: nil, username: nil, created_at: nil, updated_at: nil>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With