What is the proper way to update a record in Ruby on Rails? Just a single record. For example, I want to modify the name of the title somehow. A code snippet would be awesome!
2 回答
The basic way to update a record is like that :
@user.name = "new name"
@user.save
this assumes that @user
in an instance of a User
class having a name
field.
you can also do mass_assignment with the update_attributes
method
@user.update_attributes name: "new name", email: "new_email@foo.com"
If you want an exception to be raised if the record is invalid you can use the bang method instead, so here it would be save!
& update_attributes!
You can also use the update_attribute
which has been (or will be soon) renamed to update_column
to update a single column while skipping the validation, but you should generally avoid using this method
more doc there
Finally you can use the write_attribute method
entity = Entity.find_by_name("some_name")
entity.title="new title"
entity.save!
or
Entity.find_by_name("some_name").update_attributes(:title => "new title")
for more details, refer to http://guides.rubyonrails.org