Nancy Moore
Nancy Moore

Reputation: 2470

how to properly display image from database in ruby on rails

Am new to ruby on rails. Here Am trying to display image from database. To this effect, I leverage solution found here link. but when I run my script it displays error

No route matches {:action=>"show", :controller=>"attachments_controller", :id=>17} Please what am I doing wrong with the route. Routes

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) %>

Upvotes: 0

Views: 760

Answers (2)

Nsoseka
Nsoseka

Reputation: 319

change

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

to

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

Upvotes: 0

Mark
Mark

Reputation: 6445

The error message you provided states:

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

The routes file you provided shows the routes you created:

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

Running rake routes will show that you've created the 4 routes in the first line, plus a route that responds to 'attachments/show'. If you really want to define the route like this, you should try:

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

Your first route only responds to the word show, and would supply no params. The last route will take whatever comes after attachments, and pass it to the show action of the attachments controller as a paramater called 'id'.

Of course the easiest way to do all of that is to get rid of it all, and simply change the first route to:

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

Letting rails create the show route for you is exactly the same as manually defining it, and obviously reads a lot better

Upvotes: 3

Related Questions