Rails - Saving Ransack Query for later use

£可爱£侵袭症+ 提交于 2019-12-04 17:06:36
iubbba08

I think in the database you are storing the query as String.While you are pulling it from database @saved_search.query_parameters is returning you the string.But the ransack needs it to be a Hash.This is the main problem I guess.

While you are passing through params its gets a Hash but from database its getting String.You need to parse the string you are getting from the @query variable and then pass it to the search.

For String to Hash conversion you can have a look at How do I convert a String object into a Hash object? question's answers.

przbadu

As per your question:

{"g"=>{"0"=>{"m"=>"and", "c"=>{"0"=>{"a"=>{"0"=>{"name"=>"total_revenue"}}, "p"=>"gt", "v"=>{"0"=>{"value"=>"1000"}}}}}}, "s"=>{"0"=>{"name"=>"stock_health", "dir"=>"asc"}}}

this is how your param HASH looks like and you are storing it for future use(bookmark). The problem here is, these are storing as string in your database.

Two solution that I can suggest is:

1. USE HStore (http://www.postgresql.org/docs/9.0/static/hstore.html)

you can use HStore type column in your postgresql database to store those param hash which you can call as it is when required. NOTE: PostgreSQL database.

2. STRING to HASH conversion:

How do I convert a String object into a Hash object?

NOTE I do not recommend using eval() function, coz eval is not safe and we can't trust params

RECOMMENDATION:

another workaround for you problem I have figure out is:

1) Before saving your bookmark params, convert them to json

# suppose bookmark is a column you are using in SavedSearch table to store those ransack search params[:q] then

bookmark = {"g"=>{"0"=>{"m"=>"and", "c"=>{"0"=>{"a"=>{"0"=>{"name"=>"total_revenue"}}, "p"=>"gt", "v"=>{"0"=>{"value"=>"1000"}}}}}}, "s"=>{"0"=>{"name"=>"stock_health", "dir"=>"asc"}}}

@saved_search = SavedSearch.new(save_search_params)
@saved_search.bookmark = bookmark.to_json
@saved_search.save

2) Now, before passing these values to ransack search, convert them into original hash by:

require 'json'
@saved_search = SavedSearch.find(id)
original_bookmark = JSON.parse(@saved_search.bookmark)

I hope, this will help you solve your problem....

Try this gem: https://rubygems.org/gems/ransack_advanced_search is provides a nice interface for building queries and also allow you to name and store the search for later use. Is uses the serialize method from active_record to save the query params from the database

class SavedSearch < ActiveRecord::Base
  validates_presence_of :context, :description, :search_params

  serialize :search_params
end

It will automatically convert the search_params back to a hash when you read it from the database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!