Question

I have Ransack search with Ancestry categories.

I have the models category, page and category_page. Categories has Ancestry. Now I can search pages that has a specific category. However, what I would like to have is to show the pages that has one category and also the pages that has the children categories.

For example, if I search the Programming category, I would like also to see the pages that Ruby on Rails as category (which has Programming as parent)

Ancestry docs have several options that I can test but I don't have any idea what I have to do on Ransack. I would appreciate any recomendations that I can try out.

Snipped from PagesController

def index
  @search = Page.paginate(:per_page => 20, :page => params[:page]).search(params[:q])
  @pages = @search.result(:distinct => true)
  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @pages }
  end
end

Snipped from a view

<%= search_form_for @search, :html => {:class => "form-inline"} do |f| %>
  <%= f.label :category_id %>
  <div class="form-group" id="div_q_categories_id_eq">
    <%= f.collection_select :categories_id_eq, Category.order(:name), :id, :name, {:include_blank => true}, {:class => 'form-control'} %>
    <% "f.collection_select :categories_id_eq, Category.order(:name), :id, :name, {:include_blank => true}, {:class => 'form-control', :multiple => true}" %>
  </div>
  <%= f.submit t("basic.search"), :class => "btn btn-info" %>
<% end %>
Was it helpful?

Solution

mix your search form with normal parameters like

<%= search_form_for %>
...other search field
<%= select_tag :category_id,...%>
<% end%>

then in your controller,

@q = Page.search(params[:q])
@pages = @q.result()
if params[:category_id].present?
   all_category_ids = Category.find(params[:category_id]).descendant_ids
   @pages= @pages.where(:category_id => category_id)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top