Search code examples
ruby-on-railsmigrationgsubsti

Migration issue with trying to change attributes using gsub


I have a table called items. I want to change the description attribute (it's a text attribute) for 9 of the objects. Specifically, these objects are a subclass to Item -- called Juice. So the items table is STI. Here's a sample description of the item:

Boost all payouts by 20%.

Now, when I try to run the following migration, I can't get the dang description to update. Any ideas? (Rails version is 2.3.11.)

class ModifyItemJuiceDescription < ActiveRecord::Migration

  def self.up
    juices = Juice.all

    Juice.transaction do
      for j in juices do
        puts "Juice description is: #{j.description}."
        j.description.gsub!('payouts', 'winnings')
        puts "Juice description will be saved as: #{j.description}."
        j.save!
        puts "Juice description is now: #{j.description}."
        puts "======================================================"
      end
    end

  end

  def self.down
    juices = Juice.all

    Juice.transaction do
      for j in juices do
        puts "Juice description is: #{j.description}."
        j.description.gsub!('winnings', 'payouts')
        puts "Juice description will be saved as: #{j.description}."
        j.save!
        puts "Juice description is now: #{j.description}."
        puts "======================================================"
      end
    end

  end

end

Solution

  • I have a hunch that j.description returns a copy of the string, not the actual structure that maps to the database; The gsub! call changes the wrong object.

    Try j.description = j.description.gsub(...)