How do I force ActiveRecord to reload a class?

Ruby on-RailsRubyActiverecordMigration

Ruby on-Rails Problem Overview


I'm creating a bunch of migrations, some of which are standard "create table" or "modify table" migrations, and some of which modify data. I'm using my actual ActiveRecord models to modify the data, a la:

Blog.all.each do |blog|
  update_some_blog_attributes_to_match_new_schema
end

The problem is that if I load the Blog class, then modify the table, then use the Blog class again, the models have the old table definitions, and cannot save to the new table. Is there a way to reload the classes and their attribute definitions so I can reuse them?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

The answer is yes!

Blog.reset_column_information

Solution 2 - Ruby on-Rails

I always used new models in migrations

    MyBlog < ActiveRecord::Base
      set_table_name 'blogs'
    end

    def self.up
      MyBlog.all.each do |blog|
        update_some_blog_attributes_to_match_new_schema
      end
    end

But Blog.reset_column_information is more convenient.

Solution 3 - Ruby on-Rails

Create new instances:

Old_blogs = Blog.all

> # change/modify db table in here

New_blogs = Blog.all # this should be reloaded or you could use the .reload on this

> # change information, load old into new

ex.

Old_blogs.each do |blog|
  New_blogs.find(blog.id).title = blog.title
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames A. RosenView Question on Stackoverflow
Solution 1 - Ruby on-RailsJames A. RosenView Answer on Stackoverflow
Solution 2 - Ruby on-RailsVitalieView Answer on Stackoverflow
Solution 3 - Ruby on-RailsJon SmockView Answer on Stackoverflow