Ransack Rails - One parameter in Array - ruby-on-rails

I'm a total beginner in Rails and I try to use Ransack to filter results.
I have a model called 'adventures' which has many parameters, of which 'main_activity'. I try to implement a form in my homepage, where you can type the kind of activities you are looking for (later I will implement a dropdown so it will be limited to existing activities).
Here is what I have in my pages_controller:
def search
if params[:search].present? && params[:search].strip != ""
session[:bourse_aventuriers_search] = params[:search]
end
arrResult = Array.new
if session[:bourse_aventuriers_search] && session[:bourse_aventuriers_search] != ""
#adventures_main_activity = Adventure.where(active: true).all
else
#adventures_main_activity = Adventure.where(active: true).all
end
#search = #adventures_main_activity.ransack(params[:q])
#adventures = #search.result
#arrAdventures = #adventures.to_a
end
And in my home.html.erb
<%= form_tag search_path, method: :get do %>
<div class="row">
<div class="col-md-6">
<%= text_field_tag :search, params[:search], placeholder: "Quelle activité ?",
class:"form-control" %>
</div>
For the moment, whatever I type in the form, I get all the 'adventures' in the data base ; I find it logical because I did not change the 1st #adventures_main_activity = Adventure.where(active: true).all.
I don't know how to change it so that It will give me only the adventures whose main_activity is the keyword that I type in the form. Can anyone help me ? Thanks :)

I think you have a lot of surplus code in your search. Your controller should only need the #q parameter as follows:
#q = Adventure.ransack(params[:q])
#adventures = #q.result
The #adventures will then return any matches as an active record.
If you pass no parameters then the query will return all records (same as doing an Adventure.all).
When you submit the form the ransack search will pass a "q" param which will contain all the form items. Your's may look something like this:
"utf8"=>"✓", "q"=>{"search_cont"=>"rock climbing"}, "commit"=>"Search", "controller"=>"adventures", "action"=>"index"
If you use a debugger you can see this information by typing "params" in the command line. It will also appear in the server output.
Using an example of one I did in my application here is the exact code I used:
View:
<%= search_form_for #q do |f| %>
<div class="form-group col-sm-6">
<%= f.label :email_cont, "Email:" %>
<%= f.search_field :email_cont, :placeholder => "Please enter and email to search for", :class => "form-control" %>
</div>
<div class="form-group col-sm-3">
<%= f.submit 'Search', :class => 'btn btn-primary' %>
<%= link_to 'Reset', users_path, :class => 'btn btn-default' %>
</div>
<% end %>
Controller
def index
#q = User.ransack(params[:q])
#users = #q.result(distinct: true).order(:email).page params[:page]
end
The classes are just Bootstrap CSS which you won't need if you are not using bootstrap.
EDIT
The search_form_for #q has to exactly that and the #q has to be set in the params for it to work. Ransack is very specific about them. So your #search in
#search = #adventures_main_activity.ransack(params[:q])
should be #q. In your view change your form_tag to search_form_for and it should work. Good luck.

Related

Rails 5: search by keyword and sort by distance

I have a search form on my app:
<%= form_for search_path, method: :get do |f| %>
<p>
<%= f.label "Search for" %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "search", name: nil %>
</p>
<% end %>
that searches by distance:
def search
if params[:search].present?
#las = La.near(action,10).reorder('distance')
else
#las = []
end
end
The results are sorted by distance and all works well up to here!! The only issue here is that the results do not appear according to the keyword typed as well. Thus whatever keyword I type, all results appear and sorted by distance.
Any idea what I might be doing wrong here??
You could try passing the content of params[:search] within the near scope:
#items = Item.near(params[:search], 10).reorder('distance')

Search form for Paper_trail history using Ransack gem

I'm struggling to get a search form for my active record history.
I'm using the paper_trail gem as well as ransack. Both, alone, are working well. But whenever I try to implement a search form I get a strange error:
undefined method `paper_trail_versions_path' for #<#:0x007fede31da910>
This line from my views gets highlighted:
<%= search_form_for #q, html: {class: "input-group"} do |f| %>
Here's the code of the controller:
def history
#all_versions = PaperTrail::Version.order('created_at DESC')
#versions = #all_versions.paginate(:page => params[:page], :per_page => 100)
#q = #versions.search(params[:q])
#versions = #q.result
respond_to do |format|
format.html
end
end
the views:
<%= search_form_for #q, html: {class: "input-group"} do |f| %>
<%= f.search_field :whodunnit_or_item_id_cont, placeholder: "Search for Users or Actions..", class: "form-control" %>
<span class="input-group-btn">
<%= button_tag(type: 'submit', class: "btn btn-default") do %>
<i class="fa fa-search"></i>
<% end %>
</span>
<% end %>
Any Ideas?
Thanks in advance!
EDIT resolved, thanks to answer:
<%= search_form_for #q, html: {class: "input-group"}, :url => "/dashboards/history/" do |f| %>
The error your see comes from the URL the search_form_for helper tries to guess for your form's action.
Under the hood, Ransack uses the polymorphic_path rails helper, which is, according to the doc, a method
for smart resolution to a named route call when given an Active Record model instance
In your case, your model is a PaperTrail::Version, which resolves to paper_trail_versions_path.
To fix the error, you can either :
define the corresponding resource in your routes.rb file, so that the helper is defined
manually define the helper
provide to the search form a url option, with the path to your form's action.
Hope it helps!

Rails - Simple search function

I'm fairly new to rails and am building an online shop just to write some rails. I'm in the process of implementing a simple search function at the moment and get some strange behaviour I can't explain.
Model method:
def self.search(query)
where("title like ?", "%#{query}%")
end
Controller methode:
def index
if params[:search]
#products = Product.search(params[:search])
else
#products = []
#Only lists available products (in cart counts as available)
#available_items = Item.where(user_id: nil).select(:product_id).uniq
#available_items.each do |item|
#products << item.product
end
end
end
Search form:
<%= form_tag(products_path, :method => "get", id: "search-form", enforce_utf8: false) do %>
<%= text_field :search, params[:search], placeholder: "Search..." %>
<%= submit_tag "Search", :name => nil %>
<% end %>
When I trigger a search I get no results and the url looks like this:
http://localhost:3000/products?search%5B%5D=Paper
When I remove '%5B%5D' from the url it all works fine and I get my results. '%5B%5D' stands for '[]' in URI encoding, can't figure out where that come from though. Any help would be greatly appreciated!
Best,
Paul
See reference how text_field and reference for text_field_tag helper works:
<%= text_field :search, params[:search], placeholder: "Search..." %>
It will give you search input field with name=search[], thats why its passing search[]='text'.
<input type="text" name="search[]" placeholder="Search..." />
Use text_field_tag instead:
<%= text_field_tag :search, params[:search], placeholder: "Search..." %>

Using a Method from Controller in Another Rails

I am using elasticsearch on my rails 4 app to search through my articles.
However, when an article is not found it redirects to a page where it alerts the user that no results are found, and allows to request a page. Instead of it saying "no results found" I want it to say "no results for ______ found" in which is takes the search bar query.
I have defined a method in the articles_controller in order to get the query but it won't show up on the page since the "no results page" uses a different controller.
What would be the best way to pull the method onto another controller or view in this case? Having trouble finding a straight forward answer for what I am trying to do. Thank you very much.
articles_controller:
def index
if params[:query].present?
#articles = Article.search(params[:query], misspellings: {edit_distance: 1})
else
#articles = Article.all
end
if #articles.blank?
return redirect_to request_path
end
get_query
end
private
def get_query
#userquery = params[:query]
end
new.html.erb (view for "no results found" page. Uses a different controller than articles page):
<body class="contactrequest">
<div class="authform" style="margin-top:15px">
<%= simple_form_for #request, :url => request_path do |f| %>
<h3 style = "text-align:center; color:red;">No results found. <%= #userquery %></h3>
<h1 style = "text-align:center; color:black;">Request a Page</h1>
<h5 style = "text-align:center; color:black; margin-bottom: 25px;">Our experts will gather the information,<br> and have your page us ASAP!</h5>
<%= f.error_notification %>
<div class="form-group">
<%= f.text_field :email, placeholder: 'Email', :autofocus => true, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.text_field :subject, placeholder: 'Item / Page Requested', class: 'form-control' %>
</div>
<div class="form-group">
<%= f.text_area :content, placeholder: 'Any additional details...', class: 'form-control', :rows => '5' %>
</div>
<%= f.submit 'Request it', :class => 'btn btn-lg btn-danger btn-block' %>
<% end %>
As you can see I've tried calling that #userquery method to display on the view page, but it doesn't show up since it's defined on a different controller. Any recommendations would be awesome.
I would suggest you render results and no results from the same controller/view. A nice clean way to do this is with partials. Your view could look something like:
<% if #articles.blank? %>
<%= render 'no_results' %>
<% else %>
<%= render 'results' %>
<% end %>
Then, you would simply create _no_results.html.erb and populate it with your current new.html.erb contents and do the same for your nominal results page (with partial _results.html.erb).

Ransack search for integer and string values from single search field

I am using Rails 4 with Ransack.
I cant make to work searching for integer and string values.
So far I tried this code.
In view:
<%= search_form_for #search do |f| %>
<div class="field">
<%= f.label :name_cont, "Nepieciešama meklēšāna pēc ID, vārda un telefona nr" %>
<%= f.text_field :name_or_phone_number_cont_or_id_eq, :placeholder => 'Meklēt pēc ID,vārda vai tel.nr.' %>
</div>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>
In controller :
def index
#search = Advertisement.search(params[:q])
#advertisements = #search.result
respond_with(#advertisements)
end
This gives me error:
undefined method `name_or_phone_number_cont_or_id_eq' for
Is there any workaround to this problem?
Or I need to convert id to string for search purposes ?
Thanks in advance.
you need to add the code to your model, for you to be able to search for string and integer.
ransacker :id do
Arel.sql("to_char(\"#{table_name}\".\"folio\", '99999999')")
end

Resources