I have a model called Agency.
One of the rows from an Agency active record looks as follows:
#<Agency id: 1, name: "Hello", contact_person: "Abhimanyu", phone_number: "946159", email: "[email protected] ", local_package: false, outstation: true, remarks: nil, status: 1>
Here I want to change the value of status
to 0
. How can I do that?
4 Answers
Ruby on Rails provides many methods for updating an activerecord. You can get differences of each method from this blog post.
agency = Agency.find(1)
agency.update(status: 0)
agency.update_attribute(:status, 0)
agency.update_column(:status, 0)
agency.update_columns(status: 0)
You can also use this
Agency.find(1).update_column(:status, 0)
You need the update_column
method. Try this:
agency = Agency.find(1) agency.update_column(:status, 0)
You should spend some time reading the Ruby on Rails Guides.
To update, you can use:
agency.update_column(:status, 0)
But update_column will ignore all the validations that you may have on your model.
If you don’t want to ignore your model validations, I recommend you to use:
agency.update status: 0
The method update_attributes is deprecated on rails 6 (https://blog.saeloun.com/2019/04/15/rails-6-deprecates-update-attributes.html)
To find the record that you want to update, you can use .find
or .where
methods. If you can find by ID use:
agency = Agency.find(1)
If you need to find by other fields, use .where
:
agency = Agency.where(email: '[email protected]').first
The .first
is used since the .where
will return a Array with objects, and you need to select an object inside. If the object that you want isn't the first one, you can use .last
.
ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoa25qZWeGeYCOoaawZZOWu261jK6nnZmkmnqiedKpnJyhlp6wbq%2FOpaympl2eu26tzWaYnKyZq7KzscKoqZ1lmaN6s8HBsmSopl2nrqq40g%3D%3D