如何使用 Paperclip 以编程方式设置文件上传 [英] How to set a file upload programmatically using Paperclip

查看:23
本文介绍了如何使用 Paperclip 以编程方式设置文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 rake 任务,使用 faker gem 为应用程序提供随机数据.然而,我们也有图片(如徽标)要上传到这个 rake 任务中.

I have a rake task to seed an application with random data using the faker gem. However, we also have images (like logos) that we want uploaded in this rake task.

我们已经设置好了 Paperclip,但是没有办法在 rake 任务中以编程方式上传它们.有什么想法吗?

We already have Paperclip set up, but don't have a way to upload them programmatically in a rake task. Any ideas?

推荐答案

您所说的以编程方式是什么意思?您可以设置一个方法,该方法将采用

What do you mean by programmatically? You can set up a method that will take a file path along the lines of

my_model_instance = MyModel.new
file = File.open(file_path)
my_model_instance.attachment = file
file.close
my_model_instance.save!

#attachment 来自我们模型中的 Paperclip 声明.在这种情况下,我们的模型看起来像

#attachment comes from our Paperclip declaration in our model. In this case, our model looks like

class MyModel < ActiveRecord::Base
  has_attached_file :attachment
end

我们在启动项目时做过类似的事情.

We've done things similar to this when bootstrapping a project.

这篇关于如何使用 Paperclip 以编程方式设置文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆