Question

I'm trying to write a very simple Rails migration that adds a new column to the table and populates it with a combination of data from other columns. However, the column gets added but the column value is nil for every record. What am I doing wrong?

class AddNameToPermissions < ActiveRecord::Migration
  def change
    add_column :auth_permissions, :name, :string
    Auth::Permission.reset_column_information
    Auth::Permission.all.each do |permission|
      target_name = permission.target_symbol || permission.target_class
      permission.name = permission.action << ", " << target_name
      permission.save
    end
  end
end
Was it helpful?

Solution

Calling permission.save will execute all the callbacks including validators and maybe a validator is preventing the record to be saved. To skip validators you can use update_column instead of save

permission.update_column(:name, permission.action << ", " << target_name)

Also I would recommend you a couple of tips:

  • Use Auth::Permission.find_each instead of Auth::Permission.all.each (this loads all the records at once in memory)
  • Try to update the permission in a rake task and use only the migration to modify the table (it is the recommended good practice way)

OTHER TIPS

Unless you are using the default option in a migration, it is usually advisable to do that in a custom rake task. Content Migrations are a bit of an anti pattern. The main Logic you want there is anything that has to deal with the schema of your database. Run your migration with only the add_column line, and then write a rake task to transfer the values from one table to the other.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top