【问题标题】:How can I insert image paperclip data into my database?如何将图像回形针数据插入我的数据库?
【发布时间】:2014-04-26 15:52:40
【问题描述】:

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

总共有一个资源。第一次迁移到照片资源会添加两列。一个 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

当前错误。如何将种子数据放入此表中?

【问题讨论】:

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


    【解决方案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

    【讨论】:

      【解决方案2】:

      试试这个:--

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-20
        • 2015-02-20
        • 2011-07-22
        • 1970-01-01
        • 2019-09-12
        • 2020-01-21
        相关资源
        最近更新 更多