在我的rails应用程序中获取nil类错误

时间:2016-01-01 20:26:30

标签: api ruby-on-rails-4 instagram instagram-api

我正在尝试从我的rails应用中的instagram API中提取图片,目前我遇到了错误:

undefined local variable or method 'search'

我的观点

<div class="container">
        <div class="row">
            <% search.each do |instagram| %>
            <%= image_tag instagram.images.low_resolution.url %>
            </div>
            <% end %>
        </div>

我的控制器

  class PagesController < ApplicationController

  def home
    access_token = "hidden"
    client = Instagram.client(access_token: access_token)
    default_search = client.tag_search('travel')
    search_query = client.tag_search(params[:q])

   if params[:q]
        search_query = client.tag_search(params[:q])
        @tag = search_query.present? ? search_query : default_search
    else
      @tag = tag.first.name
      @search = client.tag_recent_media(@tag)
  end

end
  def about
  end
end

3 个答案:

答案 0 :(得分:0)

搜索从未在您的控制器中定义...我认为您的意思是@tag,因为这是在您的控制器中定义的,可能意味着您的观点?

尝试将您的观点更改为:

  <div class="container">
    <div class="row">
        <% @tag.each do |instagram| %>
        <%= image_tag instagram.images.low_resolution.url %>
        </div>
        <% end %>
    </div>

答案 1 :(得分:0)

试试这个

在视图中

<div class="container"> 
  <div class="row"> 
    <% @search.each do |instagram| %>
      <%= image_tag instagram.images.low_resolution.url %>
     <% end %>
  </div> 
</div>

控制器

class PagesController < ApplicationController
  def home
    access_token = "hidden"
    client = Instagram.client(access_token: access_token)
    default_search = client.tag_search('travel')
    search_query = client.tag_search(params[:q])
    if params[:q]
     search_query = client.tag_search(params[:q])
     @tag = search_query.present? ? search_query : default_search
     @search = client.tag_recent_media(@tag)
    else
      @tag = default_search.first.name
      @search = client.tag_recent_media(@tag)
    end 
  end
end

答案 2 :(得分:0)

控制器:

class PagesController < ApplicationController
  def home
    access_token = "token"
    client = Instagram.client(access_token: access_token)
    default_search = client.tag_search('travel')


    if params[:q] 
      search_query = client.tag_search(params[:q])
      @tag = search_query.present? ? search_query : default_search

    else 
      @tag = default_search 
    end

    @tag = @tag.first.name
    @search = client.tag_recent_media(@tag)



  end

  def about
  end

end