Ruby-on-rails 如何使用 Paperclip 以编程方式设置文件上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1397461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:43:50  来源:igfitidea点击:

How to set a file upload programmatically using Paperclip

ruby-on-railsrubypaperclipfile-upload

提问by Jaryl

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.

我有一个 rake 任务,使用 faker gem 为应用程序提供随机数据。但是,我们也有想要在此 rake 任务中上传的图像(如徽标)。

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

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

回答by theIV

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!

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

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

class MyModel < ActiveRecord::Base
  has_attached_file :attachment
end

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

我们在引导项目时做过类似的事情。

回答by jonnii

I do something like this in a rake task.

我在 rake 任务中做这样的事情。

photo_path = './test/fixtures/files/*.jpg'
Dir.glob(photo_path).entries.each do |e|
  model = Model.find(<query here>)        
  model.attachment = File.open(e)
  model.save
end

I hope this helps!

我希望这有帮助!

回答by winfred

I didn't actually have to write a method for this. Much simpler.

我实际上不必为此编写方法。简单多了。

In Model ->

在模型中 ->

Class Model_Name < ActiveRecord::Base
  has_attached_file :my_attachment,
  :params_for_attachment

In seed.db ->

在seed.db ->

my_instance = Model_name.new
my_instance.my_attachment = File.open('path/to/file/relative/to/app')
my_instance.save!

Perhaps the previous answers meant to use the name of the attachment as defined in the model (rather than writing a method Model_name.attachment). Hope this is clear.

也许之前的答案意味着使用模型中定义的附件名称(而不是编写方法 Model_name.attachment)。希望这很清楚。