Search code examples
ruby-on-railsrubyyelp

Undefined method while fetching data from json


I tried to search with Yelp API using Yelp-Ruby gem. While I have some success with fetching results, sometimes I got an error like this:

undefined method `image_url' for #

I think the JSON returned does not have image_url or image_url = nil. But I don't know how to resolve it (I'm new to rails).

Here is my Search controller:

def search
  parameters = { term: params[:term], limit: 10}
  @response = Yelp.client.search('Melbourne', parameters)
render 'location_search/new' 

end

And the corresponding results view:

<% @response.businesses.each do |business| %>
<div class="large-6 columns">
    <p><%= image_tag business.image_url %>
    <p style='color: white'><%= business.name %>
        <p style='color: white'><% business.categories.each do |category, name| %>
                                <%= name %> , 
                                <% end %>
    <p style='color: white'><%= business.rating %>
    <p style='color: white'><%= image_tag business.rating_img_url %>
</div>
<% end %>

Thank you,


Solution

  • Vuong, try using the respond_to method to check if there really is a method/attribute image_url for business. Like this:

    <% if business.respond_to?(:image_url) %>
      <p><%= image_tag business.image_url %></p>
    <% end %>
    

    In this case the image will be displayed only if the object really has the image_url method/attribute.