vkill'blog

“技术本身没有太多价值,掌握了新的思考方式才是真的收获”

rails seed / factory_girl 中使用 paperclip 保存图片

22:18 , vkill
Image model 代码如下

# cat app/models/image.rb
class Image < ActiveRecord::Base
  has_attached_file :data,
                    :url  => "/system/images/:id/:style_:basename.:extension",
                    :path => ":rails_root/public/system/images/:id/:style_:basename.:extension",
                    :styles => { :normal => ['400x300#', :png], :thumb => ['200x150#', :png] }

  validates_attachment_size :data, :less_than => 2.megabytes
  validates_attachment_presence :data
end


那么想在 seed 中保存几个图片到 Image,就这样写

# cat db/seeds.rb
#first, add  gem "content_type"  to Gemfile and bundle install, http://rubygems.org/gems/content_type
attachment_file = "#{Rails.root}/public/images/rails.png"
attachment = {
  :original_filename => File.basename(attachment_file),
  :content_type => File.content_type(attachment_file),
  :tempfile => File.open(attachment_file, 'rb')
}
data_obj = ActionDispatch::Http::UploadedFile.new(attachment)
data_obj.original_filename = attachment[:original_filename]
data_obj.content_type = attachment[:content_type]
Image.create!(:data => data_obj)



后记:
使用 fixture_file_upload

include ActionDispatch::TestProcess
Image.create :data => fixture_file_upload("/root/profile.jpg", 'image/jpg')


结合 factory_girl 使用如下

include ActionDispatch::TestProcess
FactoryGirl.define do
  factory :attachment do
      name { Faker::LoremCN.word }
      describtion { Faker::LoremCN.word }
      data { fixture_file_upload(Rails.root.join('public', 'images', 'rails.png'), 'image/png', :binary) }
      download_times { rand 1_000 }
    end
end

Last modified by vkill on2011/09/12 01:33
类别:ruby & rails | Tags: , , , , , , , , | 0 条评论, 2058 次阅读
网友评论(0):
发表评论:

Nickname: 
Email:
Site URI: