# Controlling attribute mass assignment in the controller

**URL:** <https://www.ruby-forum.com/t/controlling-attribute-mass-assignment-in-the-controller/115753>\
**Category:** Rails\
**Created:** [September 28, 2007, 6:27am UTC](https://www.ruby-forum.com/t/controlling-attribute-mass-assignment-in-the-controller/115753 "2007-09-28T06:27:49Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pete](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/3ab097/32.png) [@pete](https://www.ruby-forum.com/u/pete)\
**Post date:** [September 28, 2007, 6:27am UTC](https://www.ruby-forum.com/t/controlling-attribute-mass-assignment-in-the-controller/115753/1 "2007-09-28T06:27:49Z")

</div>

Rails nicely lets me do this in a controller:

```
 @user = User.new(params[:user])

```

and provides the attr\_protected (and attr\_accessible) model methods to  
hide attributes from this sort of the mass assignment.

Problem is, I quite often want to control which attributes are assigned  
on a per-action basis, which leaves me doing things like:

```
 @user = User.new
 @user.name = params[:user][:name]
 @user.address = params[:user][:address]

```

Not very DRY. The alternative that I’ve been using recently is this:

```
 @user = User.new(params[:user].only(:name, :address))

```

where the “only” method is defined as:

```
 class Hash
   def only(*keys)
     keys.map!(&:to_s)
     Hash[*self.select {|key, value| keys.include?(key) }.flatten]
   end
 end

```

Do you think this is a nice way to do it? Got suggestions for  
alternatives or improvements?

Regards,

Pete Y.

> **[Pete Yandell — Principal Engineer / Architect](https://notahat.com/)**
>
> Pete Yandell is an experienced Principal Software Engineer and Architect based in Melbourne, Australia.

---

<div class="post-metadata">

**Author:** ![pete](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/3ab097/32.png) [@pete](https://www.ruby-forum.com/u/pete)\
**Post date:** [September 28, 2007, 12:12pm UTC](https://www.ruby-forum.com/t/controlling-attribute-mass-assignment-in-the-controller/115753/2 "2007-09-28T12:12:27Z")

</div>

Pete :

> ```
> end
> end
> 
> ```
> 
> Do you think this is a nice way to do it? Got suggestions for  
> alternatives or improvements?

Have a look at ActiveSupport’s Hash#slice in Edge :

[http://dev.rubyonrails.org/browser/trunk/activesupport/lib/active\_support/core\_ext/hash/slice.rb](http://dev.rubyonrails.org/browser/trunk/activesupport/lib/active_support/core_ext/hash/slice.rb)

Hash#assert\_valid\_keys as a guard can also be useful.

– Jean-François.

–  
Ruby ( [http://www.rubyfrance.org](http://www.rubyfrance.org) ) on Rails ( [http://www.railsfrance.org](http://www.railsfrance.org)  
)
