Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

How can I update a specific column in an activerecord in Ruby on Rails?

Writer Emily Wong

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?

1

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)
  1. update

    agency.update(status: 0)
  2. update_attribute

    agency.update_attribute(:status, 0)
  3. update_column

    agency.update_column(:status, 0)
  4. update_columns

    agency.update_columns(status: 0)
3

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 ()

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.