Search code examples
ruby-on-railsransack

Save Ransack search param


I would like to display the search term a user inputs as part of the markup in the resulting page.

I was hoping the simple <%= params[:q] %> would do the trick, but that returns the predicate as well eg. {"title_or_content_cont"=>"foo"}

How can I extract just "foo"?


Solution

  • The answer by Kumar is good, though I'd go with a slightly different approach to cover occasions where params[:q] is nil.

    Were it to be nil, the following would result in an error:

    <%= params[:q][:title_or_content_cont] %>
    

    NoMethodError: undefined method `[]' for nil:NilClass

    Therefore, to process this safely you should use one of the following approaches (ref for :dig and :try):

    <%= params.dig(:q, :title_or_content_cont) %> # on newer versions of Rails
    <%= params[:q].try(:[], :title_or_content_cont) %> # on older versions
    

    This is crucial - if you don't account for this, you'll get an error whenever the search term is missing.

    Both of the above return nil if nothing is found, so you can leave it displaying nothing, or add alternative copy should nothing be found, i.e.

    <%= params.dig(:q, :title_or_content_cont) || "No search term" %>
    

    Hope this helps - let me know if you've any questions.