views:

322

answers:

4

I am new to rails so sorry if this is easy. I am wondering the best way to upload pictures and display them in Ruby on Rails. I have a blog and would like to have the option of attaching a picture when creating a post.

+2  A: 

Many people recommend PaperClip. Perhaps you want to try using that first.

jpartogi
+3  A: 

Paperclip is quite awesome. There's an excellent RailsCast about it - http://railscasts.com/episodes/134-paperclip

danpickett
+2  A: 

Assuming you don't need fancy features, don't wish to add a dependency and want to store the image as a BLOB in your DB, you can do something like:

Model:

class Image < ActiveRecord::Base
  def img=(input_data)
    self.filename = input_data.original_filename
    self.filetype = input_data.content_type.chomp
    self.img = input_data.read
  end
end

Controller:

class ImagesController < ApplicationController
  def display_img
    @img = Image.find(params[:id])
    send_data(@img.img, :type => @img.filetype, :filename => @img.filename,
              :disposition => 'inline')
  end
end

Here's a link to a more complete tutorial.

JRL
Avoid storing large blobs in the database -- there's rarely a case where it's a good idea.
bensie
A: 

attachment_fu (http://github.com/technoweenie/attachment_fu) is another option although I personally would recommend paperclip. It doesn't require Rmagick which is a big plus, and it supports some cool features like uploads to S3 with minor configuration.

samg