[RUBY] Nil location provided. Can't build URI. Resolution

Premise / What you want to achieve

We are developing a diet app as a portfolio for job change activities. I want to display an image on the image list page.

Problems / error messages that are occurring

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.

スクリーンショット 2020-08-23 午前0.02.27.png As it was pointed out, the database contains multiple posts without images.

Apparently this is the cause.

Corresponding source code

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"

What I tried (solved by this)

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.

Completed image list page

スクリーンショット 2020-08-23 午前0.09.37.png

Reference article: [Specify NOT NULL in [Rails] Where clause

Recommended Posts

Nil location provided. Can't build URI. Resolution
What to do when "Nil location provided. Can't build URI." Appears on CarrierWave