Reputation: 81
Hello I try to download a jpeg image on rails by verifying that the Post exists and by recovering its id in parameter.
I try something but i got a error... I show you:
def download
send_file '/public/uploads/posts/@image/image.jpg', :type => 'image/jpeg', :disposition => 'attachment', :x_sendfile => true
end
private
def set_image
@image = Post.find(params[:id])
end
In my controller I have to in my routes get download.
And my link_to
is:
<%= link_to "Download", download_posts_path %>
But rails say to me "Couldn't find Post without an ID". I don't understand why... He dont't have the id but I dont't know why ?
Upvotes: 1
Views: 743
Reputation: 2620
Assuming you use set_image
in a before_action
filter.
First you should pass the post
instance or id to your route helper :
If your route takes a param e.g. /posts/:id/download
:
<%= link_to "Download", download_posts_path(@post) %>
<%= link_to "Download", download_posts_path(@post.id) %>
If not you can pass it with a query parameter e.g. posts/download/?id=1
<%= link_to "Download", download_posts_path(id: @post.id) %>
Both solution will provide you a params[:id]
in your controller. Otherwise params[:id]
will be nil
and find
raises an error.
Then there's something wrong in the download
action as @DileepNandanam pointed out. You're not using your Post
instance (@image
) at all, you're just passing send_file
a string containing "@image", not the variable but just a string. You may want to use interpolation to build a valid path to your image. For example if your @image
has a :name
which could be "image.jpg"
you would do it like this:
send_file "/public/uploads/posts/#{@image.name}"
Or you could name your images with the post
id like 13.jpg
then you'll do :
send_file "/public/uploads/posts/#{@image.id}.jpg"
Or even create separate forlders with post's ids :
send_file "/public/uploads/posts/#{@image.id}/image.jpg"
Upvotes: 1
Reputation: 2895
send_file "/public/uploads/posts/#{@image.image_file_name}/image.jpg", :type => 'image/jpeg', :disposition => 'attachment', :x_sendfile => true
The method image_file_name may varies depends on the attachment you have specified on model
A better way is to use the url for attachment like
send_file @image.image.url(:original)
Upvotes: 1