1

In Rails 3.2 console I am trying to update several records to the same value.

For example:

h=Person.find_all_by_company_country("Alabama")

Now I want to change the company_country to "Texas"

For example:

h.update_attributes(company_country: "Texas")
NoMethodError: undefined method `update_attributes' for #<Array:0x00000003b01d70>

What are the options to do this?

1
  • Won't that update all the Person attributes. I just want the ones with Alabama to change Commented May 16, 2014 at 18:30

3 Answers 3

6

You could do the following:

Person.where(company_country: "Alabama").update_all(company_contry: "Texas")

See the update all docs here: http://apidock.com/rails/v3.2.1/ActiveRecord/Relation/update_all

Sign up to request clarification or add additional context in comments.

3 Comments

This works great. I keep forgetting to try to use where. Thanks
Anytime! Glad to help.
NOTE: This does not run the callbacks, including validations, for these records. It's a direct-to-database change. So if you want to ensure validity or if you have an audit trail or something that needs to know when a record changes, don't use this.
1

Replace your method find_all_by_company_country to use active record querys instead, so you can return a relation.

h = Person.where(company_country: "Alabama")

Then simply invoke:

h.update_all company_county: "Texas"

Note though that update_all does not invoke active record callbacks. If you need callbacks & validations to fire, instead use:

h.each { |record| record.update_attributes({ company_country: "Texas" }) }

Comments

1

As you can see in the output, the result from the find_all* method returns an array object, of which doesn't have the update_attributes method.

Just as an example, to modify each record of an array, you would iterate each record like this:

Person.find_all_by_company_country("Alabama").each do |record|
  record.update(:company_country => "Texas")
end

But the typical way is to perform the update with the where and update_all methods, which is far more efficient by using a single update query:

Person.where(:company_country => "Alabama").update_all(:company_country => "Texas")

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.