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?
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With