如何在 Sinatra 中使用 CarrierWave 显示图像

How to display images with CarrierWave in Sinatra

我在使用 CarrierWave 时遇到了很多困难,所以我编写了一个小程序,看看我是否可以让它工作:

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>

我从电脑上传图片时好像无法显示图片。好像图像没有保存在任何地方,因此无法检索它们。

锚标记正确地引用了图像应在的位置,但没有图像。

我做错了什么?

为@MrMos 转换为 ...

没关系,我发现了。我这样做了:

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>