Search code examples
ruby-on-railssearchruby-on-rails-4sunspot

Search in sunspot (facet)


I'm following this railscasts #278 Search with Sunspot to implement a facet search with sunspot but i'm getting this error undefined methodfacet' for nil:NilClass`

this is my article model

   searchable do
      text :title, boost: 4
      text :content
      time :created_at
      string :publish_month
    end

    def publish_month
      created_at.strftime("%B %Y")
    end

this is my search controller

def search

  @articles = Sunspot.search(article) do
    fulltext params[:query]
    with(:created_at).less_than(Time.zone.now)
    facet(:publish_month)
    with(:publish_month, params[:month]) if params[:month].present?
    end

    respond_to do |format|
      format.html { render :action => "search" }
    end
  end

this is my view for facet

<div id="facets">
  <h3>Published</h3>
  <ul>
    <% for row in @search.facet(:publish_month).rows %>
      <li>
        <% if params[:month].blank? %>
          <%= link_to row.value, :month => row.value %> (<%= row.count %>)
        <% else %>
          <strong><%= row.value %></strong> (<%= link_to "remove", :month => nil %>)
        <% end %>
      </li>
    <% end %>
  </ul>
</div>

Solution

  • Any chance you were referring to @articles instead of @search in your view?

    Try changing the line to that:

    <% for row in @articles.facet(:publish_month).rows %>