Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save Ransack searches to the database?

I'm trying to save Ransack searches to the database. I believe I should be able to just store the params[:q] value, then append that to the search URL when I want to recall the search. I don't know how to save the params[:q] value, though.

The URL that Ransack creates is something like this:

http://site.com/search?utf8=%E2%9C%93&q%5Bone%5D=something&q%5Btwo%5D=&q%5Bthree%5D=&q%5Blow_number%5D=0&q%5Bhigh_number%5D=300000&q%5Bfour%5D=&commit=Search

My route to the action that will save the search is:

match 'users/:id/saved_search_add' => 'users#saved_search_add', :as => :saved_search_add

If I use this code in the view:

<%= link_to('Save Search', saved_search_add_path(current_user, :q => params[:q])) %>

With this code in the controller:

  def saved_search_add
    @saved_search = Search.create(:query => params[:q].to_hash, :user_id => @user.id)

    respond_to do |format|
      if @saved_search.save
        format.html { redirect_to(:back) }
      else
        format.html { redirect_to(:back) }
      end
    end
  end

Then the data stored is:

--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
one: ''
two: ''
three: ''
low_number: '0'
high_number: '300000'
four: ''

So, I need to somehow format the data as it's going into the database (and perhaps also as it's coming out?)... I've read something about serializing it, but I haven't had much luck getting that to work.

How can I get params[:q] into my database, to be used later to recreate the full search URL?

like image 739
James Chevalier Avatar asked Jan 25 '13 22:01

James Chevalier


1 Answers

I ended up just using request.fullpath instead of params[:q].

The code that saves the query to the database is in the Users Controller:

def saved_search_add
  @saved_search = Search.create(:query => params[:q], :user_id => current_user.id)

  respond_to do |format|
    if @saved_search.save
      format.html { redirect_to(:back) }
    else
      format.html { redirect_to(:back) }
    end
  end
end

The code I use in my View to send the search query to the Users Controller is:

<%= link_to('Save Search', saved_search_add_path(current_user, :q => request.fullpath)) %>

The query value is stored in the database as:

/search?utf8=%E2%9C%93&q%5Bone%5D=something&q%5Btwo%5D=&q%5Bthree%5D=&q%5Blow_number%5D=0&q%5Bhigh_number%5D=300000&q%5Bfour%5D=&commit=Search

I create the link to that saved search in the View with:

<%= link_to "Saved Search", search.query %>
like image 147
James Chevalier Avatar answered Oct 12 '22 15:10

James Chevalier