Hi everyone,
I was trying to do image upload by using attachment_fu but got no
lucky. I have 2 models: album and cover. Each album is associated with
only one cover. The database is like:
create_table :covers do |t|
t.integer :album_id
t.timestamps
# the following fields are required by attachement_fu
t.integer :parent_id
t.string :content_type
t.string :filename
t.string :thumbnail
t.integer :size
t.integer :width
t.integer :height
end
create_table :albums, :force => true do |t|
t.integer :cover_id
t.string :title
end
The form is like:
<% error_messages_for :album %>
<% form_for(@album, :html => { :multipart => true }) do |f| %>
<p>
<%= label :album, :title %>
<%= f.text_field :title %>
</p>
<p>
<%= label :album, :cover %>
<%= f.file_field :uploaded_cover_data %>
<span class="hint" >
We accept JPEG, GIF, or PNG files up to 500 KB.
</span>
</p>
<p>
<%= f.submit "Create" %>
</p>
<% end %>
The controller is like:
Class AlbumController < ActiveController::Base
...
def create
@album = Album.new(params[:album])
respond_to do |format|
if @album.save_with_cover
flash[:notice] = ''Album was successfully created.''
format.html { redirect_to(@album) }
format.xml { render :xml => @album, :status
=> :created, :location => @album }
else
format.html { render :action => "new" }
format.xml { render :xml => @album.errors, :status
=> :unprocessable_entity }
end
end
end
end
The model is like:
class Cover < ActiveRecord::Base
belongs_to :album
has_attachment :content_type => :image,
:storage => :file_system,
:max_size => 1.megabytes,
:resize_to => ''384, 256>'',
:processor => "ImageScience",
:thumbnails => { :large => ''96,
96>'',
:medium => ''64, 64>'',
:small => ''48, 48>''}
validates_as_attachment
end
class Album < ActiveRecord::Base
has_one :cover
attr_accessor :uploaded_cover_data
def save_with_cover
cover = Cover.new
begin
self.transaction do
if uploaded_cover_data && uploaded_cover_data.size > 0
cover.uploaded_data = uploaded_cover_data
cover.thumbnails.clear
self.cover = cover
cover.save! # the problem occurred here
end
save!
end
rescue
if cover.errors.on(:size)
logger.info("Uploaded image is too big (500-KB max).")
errors.add_to_base("Uploaded image is too big (500-KB max)." )
end
if cover.errors.on(:content_type)
logger.info("Uploaded image content-type is not valid.")
errors.add_to_base("Uploaded image content-type is not
valid." )
end
false
end
end
end
The problem lies in "cover.save!". The failure causes the transaction
to roll back, thus no cover is stored.
The image I uploaded is 332*433 with a size of 27KB. It''s in the range
of size. Where can the problem be?
I have spent several hours on it but no luck. Can anyone give some
some clues on it?
Xiahong