How to update specific column in a activerecord on rails?

Viewed 25408

I have a model called Agency

One of the row from Agency active record looks as follows:

#<Agency id: 1, name: "Hello", contact_person: "Abhimanyu", phone_number: "946159", email: "Abhimanyu@purple.com ", 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

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 dont 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: 'Abhimanyu@purple.com').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.

Related