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!
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With