Monday, February 25, 2008

Basic flow to use rails file_column plugin

1. Create your table with a string field to store file name. For example:

create_table :products do |t|
t.string "name"
t.string "model"
t.string "image"
t.timestamps
end

2. Install file_column plugin:

script/plugin install http://opensvn.csie.org/rails_file_column/plugins/file_column/trunk

3. Install ImageMagick to your system and plugin RMagick

Visit http://rmagick.rubyforge.org/ for more detail

4. Put file_column description for model field into your model code. For example here, add to product.rb:

file_column :image, :magick => {
:versions => { "thumb" => "60x60", "medium" => "320x240"}
}

5. Generate controller and views for your model. I use rails 2.0 scaffold generator here:

script/generate scaffold product --skip-migration
add layout and authentication before_filter to product controller if needed
add _form.html.erb with form fields for new.html.erb and edit.html.erb to use
edit index.html.erb to show the list of products, such as <%= f.text_field :name %>

6. Show and upload image of product, edit in the _form.html.erb:

remove <%= f.text_field :image %>
add:
<% if !@product.id.nil? # in the case of edit %>
<%= image_tag url_for_file_column("product", "image", "medium") %>
<% end %>
<%= file_column_field "product", "image" %>

7. Add multipart to form tag in the edit and new files.

<% form_for(@product, :html => {:multipart => true}) do |f| %>

8. To show image in the list:

<% @product = product %>
<%= image_tag url_for_file_column("product", "image", "thumb") %>

2 comments:

feby artandi said...

Cool,

Thanks.

Feby A. Sukirman

Anonymous said...

Yep, useful. Thank you.

Eric.