Using Ransack in rails for searching companies and associated categories

607 views Asked by At

I have a search feature in my app where I search for a company and the results are companies fitting the name and the associated primary_categories for all of those companies.

I'm using ransack to grab the relevant companies.

Companies and PrimaryCategories have a has_many_and_belongs_to_many association. I'm refactoring the code to grab relevant primary categories from returned companies.

Below is the method before the changes.

def search
  @q = Company.ransack(name_cont: params[:q][:name], keywords_name_cont: params[:q][:name], m: 'or')
  @companies = @q.result.uniq
  @q2 = PrimaryCategory.ransack(name_cont: params[:q][:name])
  @categories = @q2.result.uniq
  @search_term = params[:q][:name]
end

On the search results page, I can retrieve the company but the primary categories are blank since I'm being returned an empty array object.

I'm looking for a clean way to extract the associated primary_categories from the returned companies

I've re-written the above method to include an array object.

def search
  @q = Company.ransack(name_cont: params[:q][:name], keywords_name_cont: params[:q][:name], m: 'or')
  @companies = @q.result.uniq
  @categories = []
  @search_categories = @companies.each {|co| @categories << co.primary_categories}
  @categories.flatten!.uniq
  @search_term = params[:q][:name]
end

This works but I want to know if I can get the same result using ransack. Is there a more efficient way to grab the associated objects using ransack instead of creating a separate categories array?

1

There are 1 answers

0
Tyrone Wilson On

For your initial question of loading companies based on name and including the categories with the companies I would just use the includes ActiveRecord option.

Company.includes(:primary_categories).ransack(...)

each company loaded will then have its primary_categories eager loaded.