rails/rails — pull request #9959 by jalkoby (2013-03-27 23:33:32+00:00)
Title: Safe migrations with activerecord features

Quite often we should change our existing data in migrations. For example, we add new column and should this column for existing records. For do that you can use application models:

```ruby
add_column :users, :agree, :boolean
User.reset_column_information
User.update_all(:agree => true)
```

Simple, but you need know `reset_column_information` method. Also if you decided change table_name to persons and model's name to Person this migration will raise exception and will no run.
Another, "right", way to solve problem of updating data in migration is using plain sql.

```ruby
execute "UPDATE users SET users.agree = 1"
```

This migration doesn't care about app models. So it will not fail if "User" model will not exist when migration will execute. But we all love activerecord because it converts ruby objects to db types, write and execute sql queries in more elegant way, automatically add a lot of useful methods based on table schema. So why we should not use it in migration?
So what about this solution:

```ruby
use_table(:users).update_all(:valid => true)
```

Method `use_table` creates unnamed activerecord model, sets table name and returns it's default scope. So we can fetch data, update it and etc.
What do you think about it?