Roger
Roger

Reputation: 3959

How to force a record to save itself even if I have not changed any attributes

In order to clean up some bad data I added a before save callback. Now I need to force all the models to be saved again. However no update operation happens if I do this

User.first.save

How do I force all the models to perform save operation even though I don't have any attributes changed.

Upvotes: 17

Views: 21673

Answers (4)

yuяi
yuяi

Reputation: 2715

You can still use touch to solve your problem, as cwninja's answer points out.

True, it doesn't trigger traditional callbacks anymore in latest Rails, as mentioned by Josh Rickard. But it does trigger the after_touch callback.

See bottom of this page:

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

Upvotes: 1

parapet
parapet

Reputation: 1827

As Josh Rickard commented to the accepted answer, since Rails 3.0.X touch does not invoke validation and callbacks anymore.

You can, however, "touch" it manually with model.update_attribute(:updated_at,Time.now) and skip validation and invoke callbacks that way.

Upvotes: 18

cwninja
cwninja

Reputation: 9778

You should be able to use touch, it fires callbacks when it saves.

Alternatively turn off partial_updates: ActiveRecord::Base.partial_updates = false

Upvotes: 26

cgr
cgr

Reputation: 1121

If the attributes aren't modified it won't save. If you modified something during the cleanup, it should be able to be saved.

Upvotes: 0

Related Questions