Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails 3, is there a difference between = and assign_attributes?

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!

like image 355
Porkcrop Avatar asked Aug 07 '12 21:08

Porkcrop


1 Answers

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).

like image 71
cjhveal Avatar answered Dec 07 '22 01:12

cjhveal