如何在轨道上的ruby中正确显示数据库中的图像

问题描述 投票:0回答:2

我是铁杆上的红宝石新手。这里我试图从数据库显示图像。为此,我利用这里找到的link解决方案。但是当我运行我的脚本时,它会显示错误

No route matches {:action=>"show", :controller=>"attachments_controller", :id=>17}请问我的路线有什么问题。路线

Rails.application.routes.draw do


   resources :attachments, only: [:index, :new, :create, :destroy]
   root "attachments#create"

   get "attachments/show" => "attachments#show"

end

attachments_controller

class AttachmentsController < ApplicationController
  def show
    @attachment = Attachment.find(params[:id])
    send_data @attachment.data, :filename => @attachment.filename, :type => @attachment.content_type
  end
end

show.html

<%= image_tag url_for(:controller => "attachments_controller", :action => "show", :id => @attachment.id) %>
ruby-on-rails ruby
2个回答
3
投票

您提供的错误消息指出:

No route matches {:action=>"show", :controller=>"attachments_controller", :id=>17}

您提供的路线文件显示您创建的路线:

resources :attachments, only: [:index, :new, :create, :destroy]
get "attachments/show" => "attachments#show"

运行rake路线将显示您已在第一行创建了4条路线,以及响应“附件/节目”的路线。如果你真的想要定义这样的路线,你应该尝试:

get "attachments/:id", to: "attachments/show"

你的第一条路线只响应show这个词,并且不提供参数。最后一条路线将采用附件之后的任何内容,并将其作为名为“id”的参数传递给附件控制器的show动作。

当然,最简单的方法就是摆脱这一切,只需将第一条路线改为:

resources :attachments, only: [:index, :new, :create, :destroy, :show]

让rails为你创建show route与手动定义它完全相同,显然读起来要好得多


0
投票

更改

<%= image_tag url_for(:controller => "attachments_controller", :action => "show", :id => @attachment.id) %>

<%= image_tag url_for(:controller => "attachments", :action => "show", :id => @attachment.id) %>