如何强制ActiveRecord重载类?

时间:2021-04-24 23:10:02

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:

我正在创建一系列迁移,其中有些是标准的“创建表”或“修改表”迁移,有些是修改数据的迁移。我用实际的ActiveRecord模型来修改数据,一个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?

问题是,如果我加载Blog类,然后修改表,然后再次使用Blog类,那么模型有旧的表定义,不能保存到新表中。是否有方法重新加载类及其属性定义,以便重用它们?

3 个解决方案

#1


124  

The answer is yes!

答案是肯定的!

Blog.reset_column_information

#2


4  

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.

但博客。reset_column_information更方便。

#3


2  

Create new instances:

创建新实例:


Old_blogs = Blog.all

# change/modify db table in here

#更改/修改这里的db表

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

#1


124  

The answer is yes!

答案是肯定的!

Blog.reset_column_information

#2


4  

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.

但博客。reset_column_information更方便。

#3


2  

Create new instances:

创建新实例:


Old_blogs = Blog.all

# change/modify db table in here

#更改/修改这里的db表

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