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_attributesorupdate(which is an alias for the deprecatedupdate_attributes):If you choose to
updateinstead, the object will be saved immediately (pending any validations, of course).