Search This Blog

Monday, April 4, 2011

Rails : saving and displaying images from database


Here is the logic to save images into blob and displaying those saved images..

Here is my database table:

| Field | Type
----------------------------------------------------------
| id | int(11)
| upload_file_name | varchar(255)
| upload_content_type | varchar(255)
| upload_file_size | int(11)
| created_at | datetime
| updated_at | datetime
| data | mediumblob
-----------------------------------------------------------

In VIEW:

<%= f.file_field :image_file, :value => "Select a file"%>

In CONTROLLER:

@uploadimages = UploadImage.new
@uploadimages.upload_file_name = params[:image_attributes][:image_file2].original_filename
@uploadimages.upload_content_type = params[:image_attributes][:image_file2].content_type
@uploadimages.upload_file_size = params[:image_attributes][:image_file2].size
@uploadimages.data = params[:image_attributes][:image_file2].read
@uploadimages.save

This will save the image into the database.

-------------------------------

Here is the code to display the saved image from the database:

In CONTROLLER:

def show_image
@image = UploadImage.find(params[:id])
send_data @image.data, :type => 'image/png', :disposition => 'inline'
end

In VIEW:

<%= image_tag url_for(:action => 'show_image', :id => images.id), :size => "300x200") %>


This will display the image!!

Validation message showing as {{attribute}} {{message}}


Typically the model validations is shown at the top of a reloaded form so the user can take action and resubmit.

Today, I started seeing the following message instead of the validation/error messages while I was testing some new functionality in a form:

{{count}} errors prohibited this {{model}} from being saved
{{attribute}} {{message}}
{{attribute}} {{message}}


This is caused coz, I had upgraded the i18n gem from 0.4.2 to 0.5.0.  All I had to do was install 0.4.2 and remove 0.5.0 and my error messages started showing correctly again.

Here is the command to uninstall the i18n v0.5.0 gem:

sudo gem uninstall i18n --version=0.5.0

And then, restart the server.. Problem solved :)