我可以通过Rails迁移为对象的图片字段设置默认图片吗?

时间:2015-09-02 10:57:09

标签: ruby-on-rails ruby imagemagick

我有一个car对象,目前没有默认图片,并且在没有用户上传的图片时会导致问题。我想制作一张默认图片,并想知道这是否有效:

class AddPictureToCars < ActiveRecord::Migration
  def change
    add_column :cars, :picture, :string, default: assets/images/default.jpg
  end
end

默认部分是我要添加的内容,不确定迁移过程中该路径是否正确。

或者,如果我需要进入ImageMagick并且编辑 Carrierwave(之前称为Paperclip的)设置为此更加强大。我该怎么办?

EDIT 的 Car.rb

class Car < ActiveRecord::Base
  belongs_to :user
  mount_uploader :picture, PictureUploader
  validates :user_id, presence: true
  validates :year, presence:true, length: { maximum: 4 }
  validates :brand, presence:true
  validates :model, presence:true
  validates :vin, presence:true, length: { maximum: 17 }
  validates :mileage, presence:true
  validate  :picture_size

  private

    def picture_size
      if picture.size > 5.megabytes
        errors.add(:picture, "should be less than 5MB")
      end
    end
end

使用default_url建议编辑 picture_uploader.rb

class PictureUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  process resize_to_limit: [380, 240]

  if Rails.env.production?
    storage :fog
  else
    storage :file
  end

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Add a white list of extensions which are allowed to be uploaded.
  def extension_white_list
    %w(jpg jpeg gif png)
  end

  def default_url(*args)
    ActionController::Base.helpers.asset_path("/images/default.jpg")
  end
end

位于assets / images / default.jpeg的默认图片

1 个答案:

答案 0 :(得分:0)

我会避免将后备图像路径存储在数据库中,因为这会使以后更改默认值更加困难。

Paperclip 允许默认(后备)图片。只需在default_url: "/images/default.jpg"配置中添加has_attached_file之类的内容即可。

请参阅:https://github.com/thoughtbot/paperclip#models

如果您使用 CarrierWave ,只需向您的上传器添加default_url方法:

class PictureUploader < CarrierWave::Uploader::Base
  def default_url(*args)
    "/images/default.jpg"
  end
end

请参阅:https://github.com/carrierwaveuploader/carrierwave#providing-a-default-url

如果您使用 AssetPipeline ,则需要使用asset_path帮助程序来构建后备网址。将此行"/images/default.jpg"更改为:

    ActionController::Base.helpers.asset_path("/images/default.jpg")