Domanda

I have followed the RailsCast on simple search forms and Heroku's full text search instructions and am using the pg_search gem.

I am trying to search through my microposts while retaining the scope I set for my index.

Here is my microposts_controller.rb index action

def index
    #@microposts = Kaminari.paginate_array(Micropost.popular).page(params[:page]).per(25)
    @micropost  = current_user.microposts.build
    @microposts = Micropost.search(params[:query]).page params[:page]
end

The commented out code is my code with the scope that I want. It works by itself but isn't able to be searched. The new assignement of @microposts works for the search, but it makes my index page lose the 'popular' scope I set for it.

Here is the micropost's index.html.erb

<%= form_tag microposts_path, method: :get do %>
    <%= text_field_tag :query, params[:query], placeholder: 'Search for a micropost' %>
    <%= submit_tag "Search", name: nil, class: "btn btn-lrg btn-primary" %>
<% end %>
<%= render 'shared/public_feed' %>

_public_feed.html.erb

<% if @microposts.any? %>
  <ol class="microposts">
    <%= render partial: 'shared/feed_item', collection: @microposts %>
  </ol>
<% end %>
<%= paginate @microposts, :theme => 'twitter-bootstrap', :pagination_class => "pagination-sm" %>

micropost.rb

def self.popular
    reorder('votes desc').find_with_reputation(:votes, :all)
end

I don't care if the search results have the 'popular' scope applied, I just want the initial visit to the index page to have the 'popular' scope before a search is performed. I was thinking maybe there is an if statement I could place somewhere in the controller or view but nothing seems to be working.

È stato utile?

Soluzione

In order to make it work I removed @microposts = Micropost.search(params[:query]).page params[:page] from the index action and put it in the search form like this

<%= form_tag microposts_path, method: :get do %>
    <%= text_field_tag :query, params[:query], placeholder: 'Search for a micropost' %>
    <%= submit_tag "Search", name: nil, class: "btn btn-lrg btn-primary" %>
       <% if params[:query].present? %>
          <% @microposts = Micropost.search(params[:query]).page params[:page] %>
       <% end %>
<% end %>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top