Monkeypatch 一个 rake 任务中的模型以使用插件提供的方法?
在最近的一些重构中,我们更改了用户头像的存储方式,但没有意识到一旦部署它就会影响所有现有用户。所以现在我正在尝试编写一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
rake 任务可能不会加载完整的 Rails 环境。您可以通过执行以下操作来强制它这样做:
路径通向您的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:
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.