Monkeypatch 一个 rake 任务中的模型以使用插件提供的方法?

发布于 2024-08-29 09:40:25 字数 650 浏览 7 评论 0原文

在最近的一些重构中,我们更改了用户头像的存储方式,但没有意识到一旦部署它就会影响所有现有用户。所以现在我正在尝试编写一个 rake 任务来通过执行类似的操作来解决此问题。

namespace :fix do

  desc "Create associated ImageAttachment using data in the Users photo fields"
  task :user_avatars => :environment do
    class User      
      # Paperclip
      has_attached_file :photo ... <paperclip stuff, styles etc>
    end

    User.all.each do |user|
      i = ImageAttachment.new
      i.photo_url = user.photo.url
      user.image_attachments << i
    end    
  end

end

当我尝试运行它时,虽然我得到了 User:Class 的未定义方法“has_attached_file”,但

我可以在脚本/控制台中执行此操作,但似乎无法从 rake 任务中找到回形针插件的方法。

During some recent refactoring we changed how our user avatars are stored not realizing that once deployed it would affect all the existing users. So now I'm trying to write a rake task to fix this by doing something like this.

namespace :fix do

  desc "Create associated ImageAttachment using data in the Users photo fields"
  task :user_avatars => :environment do
    class User      
      # Paperclip
      has_attached_file :photo ... <paperclip stuff, styles etc>
    end

    User.all.each do |user|
      i = ImageAttachment.new
      i.photo_url = user.photo.url
      user.image_attachments << i
    end    
  end

end

When I try running that though I'm getting undefined method `has_attached_file' for User:Class

I'm able to do this in script/console but it seems like it can't find the paperclip plugin's methods from a rake task.

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

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

发布评论

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

评论(1

一影成城 2024-09-05 09:40:25

rake 任务可能不会加载完整的 Rails 环境。您可以通过执行以下操作来强制它这样做:

require File.expand_path(File.dirname(__FILE__) + "/../config/environment")

路径通向您的environment.rb 文件。如果这是为了解决问题,您应该将其专门包含在此任务中,因为您可能不希望所有 rake 任务默认包含该环境。事实上,rake 任务甚至可能不是完成您想要做的事情的最佳场所。您也可以尝试在脚本目录中创建脚本。

the rake task is probably not be loading the full Rails environment. You can force it to do so by doing something like this:

require File.expand_path(File.dirname(__FILE__) + "/../config/environment")

where the path leads to your environment.rb file. If this were to fix the issue, you should include it inside this task specifically, because you probably do not want all your rake tasks to include the environment by default. In fact, a rake task may not even be the best place to do what you're trying to do. You could try creating a script in the script directory as well.

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