jay
jay

Reputation: 12495

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!

Upvotes: 39

Views: 32436

Answers (2)

rjz
rjz

Reputation: 16510

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

Upvotes: 64

Veraticus
Veraticus

Reputation: 16074

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.

Upvotes: 4

Related Questions