Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use mass assignment for everything except for one param in Ruby on Rails?

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.

like image 799
Goalie Avatar asked Dec 03 '25 15:12

Goalie


1 Answers

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>
like image 184
Oscar Del Ben Avatar answered Dec 06 '25 06:12

Oscar Del Ben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!