如何将图像回形针数据插入我的数据库?

时间:2014-04-26 04:45:05

标签: ruby-on-rails amazon-web-services amazon-s3 paperclip

我正在做这个heroku教程(https://devcenter.heroku.com/articles/ios-photo-sharing-geo-location-service#add-controller-actions),相当简单,但它遗漏了一些信息。

总共有一个资源。第一次迁移到Photo资源会添加两列。一个lat:decimal和lng:decimal。

在第二次迁移中,我得到了......

class AddAttachmentImageToPhotos < ActiveRecord::Migration
  def self.up
    change_table :photos do |t|
      t.attachment :image
    end
  end

  def self.down
    drop_attached_file :photos, :image
  end
end

所以我的架构是......

create_table "photos", force: true do |t|
  t.decimal  "lat",                precision: 15, scale: 10
  t.decimal  "lng",                precision: 15, scale: 10
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "image_file_name"
  t.string   "image_content_type"
  t.integer  "image_file_size"
  t.datetime "image_updated_at"
end

我需要在照片表中添加一些种子数据,但我不明白如何。

我已将图片wiki.png添加到我的app / assets / images文件夹中。

然后从rails控制台,我跑了......

Photo.create!(lat: 37.775, lng: -122.4183333, image: File.open("#{Rails.root}/app/assets/images/wiki.png"))

但是,这不起作用。我得到了

Paperclip::Errors::MissingRequiredValidatorError: Paperclip::Errors::MissingRequiredValidatorError
目前

错误。如何将种子数据输入此表?

2 个答案:

答案 0 :(得分:1)

您需要在模型中添加图像验证。自Paperclip 4.0以来,您必须至少验证图像的内容类型,或明确说明您不想这样做。如果不这样做,您将获得Paperclip::Errors::MissingRequiredValidatorError

Photo模型中,您需要添加以下验证器之一。

如果要验证内容类型,请执行以下操作:

validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/gif", "image/png"]

如果您只想验证文件名,请执行以下操作:

validates_attachment_file_name :image, :matches => [/jpe?g\z/, /gif\z/, /png\z/]

如果您想要明确地不验证附件的内容,那么:

do_not_validate_attachment_file_type :image

或者,如果您需要检查图像是否存在,特定类型以及不超过某个文件大小,则可以使用validates_attachment组合验证。有关详细信息,请参阅此处的文档:https://github.com/thoughtbot/paperclip

答案 1 :(得分:0)

试试这个: -

Photo.create!(lat: 37.775, lng: -122.4183333, image: File.open("#{Rails.root}/app/assets/images/wiki.png", 'rb'))