I'm using Rails 5. I have a model (with an underlying PostGres database) with some basic data columns
name | character varying |
image | bytea | not null
content_type | character varying | not null
"image" is the binary data of the image that I'd like to display. I would like to create a page to display both the image and the name but I can't figure out how to do this without multiple database calls. My show view looks like
<h1>Votes#show</h1>
<h2><%= @person.name %></h2>
<img src="<%= url_for(:controller => "people",
:action => "image",
:id => @person.id) %>" />
As you can see, to render the image, I have to call a separate controller method . The method that displays this show page is
def show
id = params[:id]
...
@person = Person.find_by_id(id)
end
and teh controller method that sends the image data is
def image
@person = Person.find(params[:id])
send_data(@person.image,
:filename => @person.name,
:type => @person.content_type,
:disposition => "inline")
end
Does anyone know how I can simplify my view so that I only need to invoke one database call to get my data instead of two?
Can you not just do this?:
<h1>Votes#show</h1>
<h2><%= @person.name %></h2>
<%= image_tag @person.image %>
Instead of sending the id back, why not send the object (you already found it)? A bit new to ruby, so not sure if this is technically correct, but it seems like you could do:
<img src="<%= url_for(:controller => "people",
:action => "image",
:id => @person) %>" />
And in the controller just use the @person object instead of looking it up again. Might want to re-name id to person or something, too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.