I am trying to implement ransack search for 3 models in a rails app that has liquid templates in the view. So far, I have been able to implement the search for just one model. In my search controller, i have;
class SearchController < ApplicationController
def index
@courses = Course.ransack(params[:q])
# @teachers = Teacher.ransack(params[:q])
# @articles = Article.ransack(params[:q])
end
end
My search.html.liquid is empty since I want the search bar to show up in the navbar. So in my navbar.html.liquid, i included this;
<form class="search" method="get" action="{{ request.url_helpers.courses_path }}">
<input type="text" placeholder="Search" name="q[title_cont]" value="" />
<input type="submit" value="Search" />
</form>
In my routes.rb, i have
resources :search, only: [:index]
Like I mentioned earlier, the search works for the Course model but i would like to include the Teacher and Article model as well. For the Teacher model, i would like to search for field "firstname_cont" and "title_cont" for the Article model.
How do I combine the search for all 3 models in one search form that works well with liquid templates?
This answer is pertinent to the ransack
portion as I have no experience with liquid and it does not seem to pertain the the question at hand
I am assuming the following
class Course < ApplicationRecord
belongs_to :teacher
has_many :articles
end
You should be able to use a compound attribute chain like title_or_teacher_firstname_or_articles_title_cont
e.g.
<form class="search" method="get" action="{{ request.url_helpers.courses_path }}">
<input type="text" placeholder="Search" name="q[title_or_teacher_firstname_or_articles_title_cont]" value="" />
<input type="submit" value="Search" />
</form>
Also your controller code is traditionally represented as:
class SearchController < ApplicationController
def index
@q = Course.ransack(params[:q])
@courses = @q.result
end
end