I would like to update attributes in an instance method in rails without being forced to change the parameters being passed in so that I can advantage of rails automatic attributes. Here is an example.
Ideal:
status = "some_new_status"
person.update(status)
class Person < ActiveRecord::Base
def update(status)
self.status = status
end
end
What I have to do now:
class Person < ActiveRecord::Base
def update(new_status)
self.status = new_status
self.save
end
end
I understand in this example it doesn't much matter. But when I have complicated update methods, it would be a lot cleaner if I could eliminate some of that code.
Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
Active Model is a library containing various modules used in developing classes that need some features present on Active Record.
Updates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.
the difference between two is update_attribute uses save(false) whereas update_attributes uses save or you can say save(true) .
You should use builtin Rails methods:
@person.update_attribute(:status, "Some Value") #no callback triggered nor validation
@person.update_attributes(:status => "Some Value") #can pass multiple values
Or to keep your short syntax
def update(status)
update_attribute(:status, status)
end
Update_attribute doc.
Update_attributes doc.
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