I'm using Ransack to run search on my app. I've got a search bar that users input text to, the text is passed to a search controller where I search for the query in two tables: Posts and Groups
The problem is that I want to run the query on :name
and :title
for Groups and Posts respectively and then serve both sets of results on the same page. The search form uses :name_cont and so I am trying to copy the hash that this form sends to the controller and change the key to :title_cont when I run the same search on Posts.
Don't hesitate to ask for clarification.
Search Controller
class SearchController < ApplicationController
def index
@q = Group.search(params[:q])
@groups = @q.result
@group_count = @groups.count
#query = params[:q][:name_cont]
posthash = { :q => {:title_cont => params[:q][:name_cont]} }
@q = Post.search(posthash)
@posts_results = @q.result(:distinct => true)
@post_count = @posts.count
end
end
Search Form:
=search_form_for @q, :url => { :controller => "search", :action => "index" }do |f|
=f.text_field :name_cont
=f.submit 'search'
Error that it yields:
undefined method `name_cont' for #<Ransack::Search:0x007fc0f798df18>
UPDATE 1:
class SearchController < ApplicationController
def index
@q = Group.search(params[:q])
@groups = @q.result
@group_count = @groups.count
#I am trying to take the query, i.e. the "value" in params[:q]
#and pass it into a new hash to use as a parameter in 'search'
posthash = { :q => {:title_cont => params[:q][:name_cont]} }
@q2 = Post.search(posthash)
@posts_results = @q2.result(:distinct => true)
@post_count = @posts.count
end
end
You're overriding @q
for searching posts, which responds to title not to name, eventually the search form gets an object that doesn't have name_cont
but title_cont
instead, so you need to use another variable name for searching posts other than @q
.