gravatar

Upload image di Rails 2.0

(Saya asumsikan platform yg digunakan Windows)

1. Buat aplikasi rails dengan perintah :
rails namaAplikasi

2. Masuk ke dalam direktori aplikasi rails yang dibuat:
cd namaAplikasi

3. Install plugin attachment_fu :
script/plugin install http://svn.techno-weenie.net/projects/plugins/attachment_fu/

4. Buat model, contoh saya akan membuat model Cover :
ruby script/generate model Cover

5. Edit file migration untuk model Cover ini, di folder db/migrate, cari 01_create_covers.rb
create_table :covers do |t|
t.integer :album_id, :parent_id, :size, :width, :height
t.string :content_type, :filename, :thumbnail
t.timestamps
end

6. Edit app/models/cover.rb. tambahkan baris kode berikut ini :
belongs_to :album
has_attachment :content_type => :image,
:storage => :file_system,
:max_size => 500.kilobytes,
:resize_to => '384x256>' ,
:thumbnails => {
:large => '96x96>' ,
:medium => '64x64>' ,
:small => '48x48>'
}
validates_as_attachment

7. Buat file app/views/covers/new.rhtml.erb

8. Edit file new.rhtml.erb
<% form_for(@cover, :html => { :multipart => true }) do |f| %>
Upload image :
<%= file_field_tag :cover_file %>
<%= f.submit "Create" %>
<% end %>

9. Buat Controller cover :
ruby script\generate controller cover

10. Di app/controllers/covers_controller.rb tambahkan code berikut :
def index
new
end

def new
@cover = Upload.new(params[:cover])
if @cover.save
flash[:notice] = 'Logo was successfully created.'
redirect_to :action => :index
else
flash[:notice] = 'Create logo failed.'
redirect_to :action => :index
end
end

wallohu'alambishowab