Home > Back-end >  How ignore empty response in ruby view loop
How ignore empty response in ruby view loop

Time:11-17

as i'm new to ruby and rails in general i would have a short question cause i'm stuck at a minor issue.

I'm calling a content API from my controller and looping thru the response in the view directly. The main problem is: If one of the objects, has an empty value which i'm calling..it breaks the view.

Question would be how can i scip the elements which are emtpy...in example if post["heroimage"]["url"] is empty?

Example view:

<div class="gallery">
<% @blog.each do |post| %>
  <a target="_blank" href="blog/<%= post["id"] %>">
    <img src="<%= @host   post["heroimage"]["url"]%>" alt="" width="600" height="400">
  </a>
  <div class="desc"><%= post['description'] %></div>
  <% end %>
</div>

CodePudding user response:

There is nothing Rails or Rails views specific about your question. What you're trying to do is skip elements in an each loop in Ruby, and the answer is, next

somethings.each do |thing|
  next if thing.nil?

  # .. does not get called if thing is nil
end

CodePudding user response:

From what I understand from the question and your comments you can use,

post.dig("heroimage", "url")

here is the link to dig method documentation. If you want to skip the image in case of empty url you can do something like this

<div class="gallery">
<% @blog.each do |post| %>
  <a target="_blank" href="blog/<%= post["id"] %>">
    <% if post.dig("heroimage", "url") %>
      <img src="<%= @host   post["heroimage"]["url"]%>" alt="" width="600" height="400">
    <% end %>
  </a>
  <div ><%= post['description'] %></div>
  <% end %>
</div>

This will still show the title even if the image URL is empty.

  • Related