sinatracarrierwavedatamapper

How to display images with CarrierWave in Sinatra


I have struggled a lot with CarrierWave, so I made a small program to see if I could make that work:

require 'sinatra'
require 'dm-core'
require 'dm-migrations'
require 'carrierwave/datamapper'

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
end

DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/photogallery.sqlite3")

class Image
  include DataMapper::Resource

  property :id, Serial
  property :title, Text

  mount_uploader :image, ImageUploader
end

DataMapper.finalize
DataMapper.auto_migrate!

get "/" do
    @images = Image.all
    erb :index
end

post "/" do
    image = Image.new(:title => params[:title])
    image.image = params[:image]
    image.save

    redirect "/"    
end

__END__

@@ index
<% @images.each do |image| %>
    <p>
        <%= image.title %>
    </p>
    <a href="<%= image.image.url %>">
        <img src="<%= image.image.url %>">
    </a>
<% end %>

<form action="/" method="post">
    <label for="title">Title</label>
    <input type="text" name="title"><br>

    <label for="image">Image</label>
    <input type="file" name="image"><br>

    <input type="submit" value="Save">
</form>

It seems that I am unable to display the image when I upload an image from my computer. It is as if the images are not saved anywhere, so they can't be retrieved.

The anchor tag correctly references where the images should be, but there are no images.

What am I doing wrong?


Solution

  • Converted to an answer for @MrMos...

    Nevermind, I found out. I did this instead:

    require 'sinatra'
    require 'dm-core'
    require 'dm-migrations'
    require 'carrierwave/datamapper'
    
    DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/development.db")
    
    class ImageUploader < CarrierWave::Uploader::Base
        storage :file
    
        def store_dir
            'images'
        end
    end
    
    class Image
        include DataMapper::Resource
    
        property :id, Serial
        property :title, Text
    
        mount_uploader :file, ImageUploader
    end
    
    DataMapper.finalize
    DataMapper.auto_migrate!
    
    get '/' do
        @images = Image.all
        erb :index
    end
    
    post '/' do
        Image.create(params[:image])
        redirect to('/')
    end
    
    __END__
    
    @@ index
    <!DOCTYPE html>
    <html>
        <body>
            <form action="/" method="post" enctype="multipart/form-data"></div>
                <input type="text" name="image[title]" />
                <input type="file" name="image[file]" />
                <input type="submit" name="submit" value="Upload" />
            </form>
            <% @images.each do |image| %>
                <p><%= image.title %></p>
                <img src="/images/<%= images.file_identifier %>" />
            <% end %>
        </body>
    </html>