Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change multiple object attributes in a single line

I was wondering, when you create an object you can often set multiple attributes in a single line eg:

 @object = Model.new(:attr1=>"asdf", :attr2 => 13, :attr3 => "asdfasdfasfd") 

What if I want to use find_or_create_by first, and then change other attributes later? Typically, I would have to use multiple lines eg: @object = Model.find_or_create_by_attr1_and_attr2("asdf", 13) @object.attr3 = "asdfasdf" @object.attr4 = "asdf"

Is there some way to set attributes using a hash similar to how the Model.new method accepts key-value pairs? I'm interested in this because I would be able to set multiple attributes on a single line like:

 @object = Model.find_or_create_by_attr1_and_attr2("asdf", 13)  @object.some_method(:attr3 => "asdfasdf", :attr4 => "asdfasdf") 

If anyone has any ideas, that would be great!

like image 824
jay Avatar asked Mar 17 '12 15:03

jay


2 Answers

You want to use assign_attributes or update (which is an alias for the deprecated update_attributes):

@object.assign_attributes(:attr3 => "asdfasdf", :attr4 => "asdfasdf")  @object.update(attr3: "asdfasdf", attr4: "asdfasdf") 

If you choose to update instead, the object will be saved immediately (pending any validations, of course).

like image 94
rjz Avatar answered Sep 28 '22 16:09

rjz


The methods you're looking for are called assign_attributes or update_attributes.

@object.assign_attributes(:attr3 => "asdfasdf", :attr4 => "asdfasf") # @object now has attr3 and attr4 set. @object.update_attributes(:attr3 => "asdfasdf", :attr4 => "asdfasf") # @object now has attr3 and attr4 set and committed to the database. 

There are some security concerns with using these methods in Rails applications. If you're going to use either one, especially in a controller, be sure to check out the documentation on attr_accessible so that malicious users can't pass arbitrary information into model fields you would prefer didn't become mass assignable.

like image 31
Veraticus Avatar answered Sep 28 '22 18:09

Veraticus