0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, that solves the name_cont error. However, I still can't figure out how to share that query between two calls to the search method in the search controller, which takes hashes as its parameter
search method just expects a hash, so you can pass the second search a hash like this Post.search({:title_cont => params[:q][:name_cont]}).
that works. you're a saint. Thank you. I also was messing up my instance variables-last line of the controller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.