1

I'm trying to write a migration to update a boolean field where the field will mean the exact opposite of what it means currently. Therefore I need to toggle every record to update the records where this field is true to false and vice-versa.

Example:

class ChangePostsVisibleToArchived < ActiveRecord::Migration[6.1]
  def change
    rename_column :posts, :visible, :archived

    # Toggle all tracked topics
    # What I DON'T want to do:
    Post.all.each { |post| post.toggle! :archived }
  end
end

The way I described above will generate one SQL command per Post record. Is there a way I can toggle all records within a single SQL command using rails ActiveRecord syntax?

2
  • 3
    UPDSTE .... SET boolcol = NOT boolcol WHERE .... Commented Aug 16, 2022 at 16:36
  • Yes @LaurenzAlbe, I can use ActiveRecord::Base.connection.execute('UPDATE posts SET archived = NOT archived') but I wonder if there's an alternative in Rails ActiveRecord. Commented Aug 16, 2022 at 19:31

1 Answer 1

2

Post.update_all "archived = NOT archived"

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

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.