5

Let's say you're in your user controller and you want to change the name a @user based on some params you have available to you.

I want to know if there is any difference between the following:

@user.name = params[:user][:name]

or

@user.assign_attributes({:name=> params[:user][:name]})

Thanks in advance!

nmc
  • 8,724
  • 5
  • 36
  • 68
Porkcrop
  • 77
  • 1
  • 8

2 Answers2

8

A great way to figure out questions like this is to dive into the source. I found the method in activerecord/lib/active_record/attribute_assignment.rbCheck it out here.

The assign_attributes method will actually just loop through the parameters given and sends the :name= message to your model. However, because you are possibly assigning many attributes, it takes into account mass-assignment precautions. (ie. make sure that the attribute is listed as attr_accessible).

cjhveal
  • 5,668
  • 2
  • 28
  • 38
3

The = (e.g. @user.name = params[:user][:name]) directly calls the attribute setter with no security check. The assign_attributes checks security for the values passed in.

From the Rails API for assign_attributes:

Allows you to set all the attributes for a particular mass-assignment security role by passing in a hash of attributes with keys matching the attribute names (which again matches the column names) and the role name using the :as option.

Source for assign_attributes

mguymon
  • 8,946
  • 2
  • 39
  • 61