> For the complete documentation index, see [llms.txt](https://ploegert.gitbook.io/til/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ploegert.gitbook.io/til/programmy/rails/ensure-migrations-use-the-latest-schema.md).

# Ensure Migrations Use The Latest Schema

Real-world migrations in Rails apps can sometimes involve both schema changes and data changes. For instance, if you are moving a column from one table to another, you'll need to add a new column, move some data, and then delete the old column.

```ruby
# Assume the following are defined:
# GenericAuthor for table 'authors'
# GenericBook for table 'books'

def up
  add_column :books, :genre, :string

  GenericAuthor.find_each do |author|
    book = GenericBook.find_by(author_id: author.id)
    book.update!(genre: author.genre)
  end

  remove_column :authors, :genre
end
```

This migration looks straightforward, but you may find that no data actually gets transferred to the `genre` column on `books`. This is because as a performance optimization, Rails has cached the scema. Thus an `ActiveRecord` modification like `book.update!` will be working off a version of the schema that doesn't include `genre` as a column.

We can ensure `ActiveRecord` is using the latest column informtion for the `books` table by calling [`reset_column_information`](https://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-reset_column_information).

```ruby
def up
  add_column :books, :genre, :string

  GenericBook.reset_column_information

  GenericAuthor.find_each do |author|
    book = GenericBook.find_by(author_id: author.id)
    book.update!(genre: author.genre)
  end

  remove_column :authors, :genre
end
```

Now the update will work and `genre` will be set on `books`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ploegert.gitbook.io/til/programmy/rails/ensure-migrations-use-the-latest-schema.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
