We are developing a diet app as a portfolio for job change activities. I want to display an image on the image list page.
Nil location provided. Can't build URI.
When I try to display the image of the post posted by current_user on the image list page, I got this error.
"Since the image is nil, I can't create the URL of the image," he says.
As it was pointed out, the database contains multiple posts without images.
Apparently this is the cause.
posts_controller.rb
posts_controller.rb
def image
@posts = Post.where(user_id: current_user.id)
end
private
def post_params
params.require(:post).permit(:food, :calorie, :protein, :fat, :carbo, :text, :image, :weight).merge(user_id: current_user.id)
end
image.html.haml
ruby:image.html.haml
.content
.images
- @posts.each do |post|
= image_tag post.image.url, class: "my-images"
Get only the post with the image.
posts_controller.rb
posts_controller.rb
def image
@posts = Post.where(user_id: current_user.id).where.not(image: nil)
end
This solved the problem if I specified that the post whose image column is nil should not be fetched.
Reference article: [Specify NOT NULL in [Rails] Where clause