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

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

问题描述

我有一个rake任务,使用faker gem为随机数据创建一个应用程序。然而,我们也有我们想要在这个rake任务中上传的图片(比如标识)。



我们已经设置了Paperclip,但是没有办法上传他们以编程方式在耙子任务。任何想法?

解决方案

你是什么意思的编程?你可以设置一个方法来获得一个文件路径:

$ my $ m $ c $ my_model_instance = MyModel.new
file = File.open(file_path)
my_model_instance.attachment =文件
file.close
my_model_instance.save!

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

  class MyModel< ActiveRecord :: Base 
has_attached_file:attachment
end

与引导项目时类似。


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.

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 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天全站免登陆