Rails项目中图片的统一存储

Wednesday, May 12, 2010

1, 创建images表

class CreateImages < ActiveRecord::Migration
  def self.up
    create_table :images do |t|
      t.string :img_file_name, :null => false, :limit => 50
      t.string :img_content_type, :null => false, :limit => 20
      t.string :img_file_size, :null => false, :limit => 20
      t.datetime :img_updated_at
      t.references :entity, :polymorphic => true
      t.integer :entity_id, :null => false
      t.string :entity_type, :null => false, :limit => 20
      t.timestamps
    end
    add_index :images, :entity_type
  end

  def self.down 
    drop_table :images 
  end 
end

2, 创建Model

class Image < ActiveRecord::Base
  belongs_to :entity , :polymorphic => true
end

3, 在Video模型中建立image关联

class Video < ActiveRecord::Base
  acts_as_taggable_on :tags
  #图片
  class Video::Image < Image
    has_attached_file :img,
      :styles => {
      :small => "120x80>",
      :medium => "200x150>",
    },
      :default_style => :small,
      :url => "/photos/videos/:id/:style/:basename.:extension",
      :path => ":rails_root/public/photos/videos/:id/:style/:basename.:extension",
      :default_url => "/images/no_picture.gif"
    validates_attachment_content_type :img,
      :content_type => [ 'image/bmp', 'image/jpeg', 'image/pjpeg', 'image/gif', 'image/png'],
      :allow_nil => true
    validates_attachment_size :img, :less_than => 1.megabytes
  end
has_one :image, :as => :entity, :dependent => :destroy, :class_name => "Video::Image"
  accepts_nested_attributes_for :image
  # ...
end

4, 页面上传

<% form_for(@video, :html => { :multipart => true, :class => "empty" }) do |f| %>

        <% f.fields_for :image do |ff| %>
          缩略图

            <%= image_tag(@video.image.img.url(:medium))%>
            <%= ff.file_field :img %>

        <% end %>

<% end %>

5, Reference

MIME TYPES:

http://www.w3schools.com/media/media_mimeref.asp

paperclip plugin:

http://github.com/thoughtbot/paperclip
yuan‘s blog: Rails文件上传利器——paperclip
笔记

This entry was tagged Rails

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top