【问题标题】:Undefined method while fetching data from json从json获取数据时未定义的方法
【发布时间】:2014-10-16 08:36:46
【问题描述】:

我尝试使用 Yelp-Ruby gem 使用 Yelp API 进行搜索。虽然我在获取结果方面取得了一些成功,但有时我会收到如下错误:

#

的未定义方法 `image_url'

我认为返回的 JSON 没有 image_url 或 image_url = nil。但我不知道如何解决它(我是 Rails 新手)。

这是我的搜索控制器:

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

结束

以及对应的结果视图:

<% @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 %>

谢谢,

【问题讨论】:

    标签: ruby-on-rails ruby yelp


    【解决方案1】:

    Vuong,尝试使用 respond_to 方法来检查是否真的有用于业务的方法/属性 image_url。像这样:

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

    在这种情况下,仅当对象确实具有image_url 方法/属性时才会显示图像。

    【讨论】:

      猜你喜欢
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 2018-12-15
      • 1970-01-01
      相关资源
      最近更新 更多