Rails 迁移脚本 VS 控制台

发布于 2024-10-07 12:32:03 字数 886 浏览 0 评论 0原文

所以我试图在迁移脚本中迁移一些数据,但数据似乎没有保存。但是,如果我复制代码并直接在控制台中运行它,它确实会保存。谁能帮我弄清楚为什么?

这是我的迁移脚本中的代码。我正在将我的头像数据从它自己的表移动到我的个人资料表中。

  def self.up
    add_column :users,    :featured,            :boolean, :default => false
    add_column :profiles, :avatar_file_name,    :string
    add_column :profiles, :avatar_content_type, :string
    add_column :profiles, :avatar_file_size,    :integer
    add_column :profiles, :avatar_updated_at,   :datetime

    Avatar.all.each do |a|
      user = User.find(a.user_id)
      user.profile.avatar_file_name = a.avatar_file_name
      user.profile.avatar_content_type = a.avatar_content_type
      user.profile.avatar_file_size = a.avatar_file_size
      user.profile.avatar_updated_at = a.updated_at
      if a.featured == true
        user.featured = true
      end
      user.save
    end

    # drop_table :avatars
  end

so i am trying to migrate some data in a migration script, but the data does not seem to be saving. however, if i copy the code and run it directly in the console, it does save. can anyone help me figure out why?

this is the code from my migration script. i am moving my avatar data from its own table into my profiles table.

  def self.up
    add_column :users,    :featured,            :boolean, :default => false
    add_column :profiles, :avatar_file_name,    :string
    add_column :profiles, :avatar_content_type, :string
    add_column :profiles, :avatar_file_size,    :integer
    add_column :profiles, :avatar_updated_at,   :datetime

    Avatar.all.each do |a|
      user = User.find(a.user_id)
      user.profile.avatar_file_name = a.avatar_file_name
      user.profile.avatar_content_type = a.avatar_content_type
      user.profile.avatar_file_size = a.avatar_file_size
      user.profile.avatar_updated_at = a.updated_at
      if a.featured == true
        user.featured = true
      end
      user.save
    end

    # drop_table :avatars
  end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如此安好 2024-10-14 12:32:03

我认为这是因为您正在更改列并尝试在同一迁移中使用它们,但模型不了解这些字段。

尝试在 Avatar.all.each 上方添加这些行...

User.reset_column_information
Profile.reset_column_information

有关此的更多信息 http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-reset_column_information

I think it's because you're changing the columns and trying to use them in the same migration, but the model doesn't know about the fields.

Try adding these lines above Avatar.all.each...

User.reset_column_information
Profile.reset_column_information

More about this http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-reset_column_information

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文