I started using Sunspot to perform searches in my Rails 3 app and I ran into a doubt. Is there a way that I can let the user choose in what fields he/she wants to search. For example, in my app we have:
class Project < ActiveRecord::Base
searchable do
text :name, :content, :keyword
end
end
And in the View the default search bar:
<%= form_tag projects_path, :method => :get do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
Can I add a radio button or something like that so the user can mark it in order just to search by name, or content or keyword? If yes, how can I make it?
Thanks a lot.
Watch the railscasts on the subject: http://railscasts.com/episodes/278-search-with-sunspot .. in it, Ryan lets user's query optionally by month.
So, if month was sent in:
def index
#search = Article.search do
fulltext params[:search]
with(:publish_month, params[:month]) if params[:month].present?
end
#articles = #search.results
end
Related
hi so I'm trying to do 2 things, one of them is to basically redirect to a model's ID number so input is "1" and redirects to
localhost:3000/model/1
and the second part is actually doing a search. each model has a text field string for license_no and I want to be able to search and return results
currently, I am not sure how I would combine these into 1 search form if thats possible or if it would require 2 separate search forms
i have a search form with only the license_no field but it always returns no results found...
apologize that the model name isn't in singular, the guide I was using to learn RoR had it that way and everything worked, but I have so many references to renters in my project that it would be a while to find all of them
index.html.erb
<%= form_tag search_renters_path, method: get do |f| %>
<%= text_field_tag :license, nil, placeholder: "License Number" %>
<%= submit_tag 'Search', class: "btn-large" %>
<% end %>
models/renters.rb
class Renters < ActiveRecord::Base
validates_presence_of :license_no
def self.search(params)
renters = Renters.where("license_no LIKE?", "%#{params[:license]}%")
end
end
controller.rb
def search
#renter = Renters.search([params])
end
search.html.erb - snippet
<% if #renter.blank? %>
no results
<% else %>
#show results
<% end %>
editted code
models/renters.rb
def self.search(params)
license_query = "%#{params[:license]}%"
id_query = "%#{params[:id]}%"
renters = Renters.where("license_no LIKE ?", license_query) if params[:license].present?
renters = Renters.where("id LIKE ?", id_query) if params[:id].present?
end
controller
def search
#renter = Renters.search(params)
end
search form
<%= form_tag search_renters_path, method: :get do |f| %>
<%= text_field_tag :license, nil, placeholder: "Driver's License" %>
<%= text_field_tag :id, nil, placeholder: "ID number" %>
<% end %>
I'm trying to use the if present? statements to allow a user to decide whether to input ID No or License No. you don't need to input both just one. currently, if I search for a license no, it returns no results. but when I search for an ID, it returns the relevant result
you can do something like this if you are getting value on params[:licence] from your form submit on your controller action search
controller.rb
def search
#renter = Renters.search(params[:licence])
end
app/models/renters.rb
class Renters < ActiveRecord::Base
def self.search(query)
like_query = "%#{query}%"
renters = Renters.where("id LIKE ? OR license_no LIKE ?", like_query, like_query)
end
end
This seems easy but I can't figure out how to do it
I'm trying to implement Ransack search in my rails app and for that I have a generated a model Cofounder which don't have any fields in it and I have association between Cofounder and CustomUser model which has email and other fields but i only want to search through email using ransack, i have this association between these two:
has_many :cofounders
belongs_to :CustomUser
(Do i need to have id if Yes how do i do it)
CoFounder Model
class Cofounder < ActiveRecord::Base
belongs_to :CustomUser
end
CofoundersController
class CofoundersController < ApplicationController
layout "custom_layout", only: [:index]
def index
#q = Cofounder.ransack(params[:q])
#cofounders = #q.result
#cofoundes = CustomUser.all
#countries = Country.all
end
end
and in my index view
<% search_form_for #q, url: cofounders_index_path do |f| %>
<%= f.search_field :email_cont, placeholder: "Search Here" %>
<%= f.submit "Search" %>
<% end %>
<%= select_tag "search_by_country", options_for_select(#countries.collect{|x| [x.name]} , params[:search_by_country] ),{prompt: "Select country"} %><br><br>
<%= select_tag "choose_a_role", options_for_select(#cofoundes.collect{|x| [x.first_name]} , params[:choose_a_role] ),{prompt: "Choose A Role", id: "select", multiple: true} %><br><br>
<% #cofoundes.each do |cofounder| %>
<%= cofounder.email %>
<%end%>
it is giving me error code
undefined method `email_cont' for #
i know email_cont if not a field in cofounder and i'm accessing that field in cofounder which is giving me error, how do i get those values in cofounder for successful Ransack search.
any help would be appreciated :)
At the moment I am trying to create a search within a project to bring up users depending on their region. From what I understand, I basically need to place the search params in the controller, the self.search method in the model, and then the form in the view.
In another project, I have a search but it shows all the options above and use the search to filter out those which do not match. For this situation, I do not want to list any users in the beginning. I want to use the search bar and bring up any users that match within that view page. Additionally I use Devise for users if that does make a difference. Here are my three regions of code:
Model (user.rb):
def self.search(search)
where("state ILIKE ?", "%#{search}%")
end
Controller (welcome_controller.rb):
def index
#users = User.all.order("created_at DESC")
#newusers = User.all.order("created_at DESC").limit(5)
#differentlocations = User.all.group_by(&:state).count
render :layout => 'with_newest_members'
if params[:search]
#users = User.search(params[:search]).order("created_at DESC")
else
#users = User.all.order('created_at DESC')
end
end
View (find.html.erb):
<%= form_tag(find_path, :method => "get") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search Posts" %>
<%= submit_tag "Search", :name => nil %>
<% end %>
Please let me know if you have any knowledge for me to help =) Any additional explanation would be greatly appreciated to help me understand, thank you!
Edit: I know I need to enter the results portion but I am confused about how/where to put it.
Joe
ANSWER:
The issue was in my controller because I had a render command prior to the search code. The controller should be:
def index
#users = User.all.order("created_at DESC")
#newusers = User.all.order("created_at DESC").limit(5)
#differentlocations = User.all.group_by(&:state).count
if params[:search]
#users = User.search(params[:search]).order("created_at DESC")
else
#users = User.all.order('created_at DESC')
end
render :layout => 'with_newest_members'
end
Fantastic =)
Two small things that might help:
1) In your Search model, I believe you have a typo in your search method. It should read as follows:
def self.search(search)
where("state LIKE ?", "%#{search}%")
end
You might also want to consider a more description name for your argument, such as state.
2) In your form, you don't need to explicitly write params[:search] anywhere. The params hash will be generated for you in the controller, with the name of the text_field as the key and the value inputted by the user as the value (see Ruby docs here). In this case, use :search as the name of the text_field_tag name.
<%= form_tag(find_path, :method => "get") do %>
<%= text_field_tag :search, placeholder: "Search Posts" %>
<%= submit_tag "Search", :name => nil %>
<% end %>
More on FormHelpers here.
I have a simple search working in my rails app, but it only searches a single column of my table. I'm trying to add a simple dropdown menu with options like "last_name" and "city" so the user can select the column to search.
In my view I have:
<%= form_tag teachers_path, :method => 'get', :id => "teachers_search" do %>
<%= hidden_field_tag :direction, params[:direction]%>
<%= hidden_field_tag :sort, params[:sort]%>
<p>
<%= text_field_tag :search, params[:search], placeholder: 'First Name' %>
<%= submit_tag "Search", :first_name => nil %>
</p>
<% end %>
and in my model:
def self.search(search)
if search
where('first_name LIKE ?', "%#{search}%")
else
scoped
end
end
Any help greatly appreciated.
You can add a select_tag for your drop down menu
<%= select_tag "search_from", "<option>first_name</option><option>last_name</option><option>city_name</option>".html_safe%>
In your controller you can pass the value in params[:search_from] to your search method. and modify it to include the column name
def self.search(search, column_name)
if search
where('? LIKE ?', column_name, "%#{search}%")
else
scoped
end
end
I've written it in a crude way but i hope it gets the message along.
extending #sohaibs's answer dropdown is a good idea if you are only allowing user to filter result with some some fixed attributes
views
<%= select_tag "search_by", options_for_select(['first_name','last_name','city'].map{|o| [o.humanize,o] }) %>
<%= f.text_field 'search' %>
controller
def search
User.search params[:teacher][:search_by],params[:teacher][:search]
end
and model
def self.search(search_by,search_value)
where('? LIKE ?', search_by, search_value)
end
Awesome Rails :)
Have you tried:
def self.search(column, search)
# some logic
where('? LIKE ?', column, "%#{search}%")
# some logic
end
Im following Ryan's Railscast 278 for searching but I am encountering an issue. In the example he uses, the controller and model are the exactly the same. Both are article. The code I have is a little different. What am I doing wrong here?
Different Model I am using:
models/compact_disc.rb
class CompactDisc < ActiveRecord::Base
searchable do
text :title
end
end
controllers/products_controller.rb
def show
#search = CompactDisc.search do
fulltext params[:search]
end
#compact_disc = #search.results
end
views/products/show.html.erb
<%= form_tag new_user_list_path, :method => :get do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<% for compact_disc in #compact_disc %>
<%= image_tag "list_images/#{compact_disc.photo_url}" %>
<%= compact_disc.title %><br/>
<% end %>
When I click search there are no results but the syntax is similiar to what he had in the Railscast.
Thanks for your help!
Your syntax is ok, but I would recommend making the search method a class method of CompactDisc:
class CompactDisc < ActiveRecord::Base
searchable do
text :title
end
def self.full_text_search(query)
solr_search do
fulltext query
end
end
end
Then in your controller you can call it like
CompactDisc.full_text_search(params[:query])
Your data might not be showing up because you haven't indexed it yet. Have you made sure to do the following in the rails console?
CompactDisk.index
Sunspot.commit
Also, depending on how your schema.xml is set up, you may need to type in the exact title in order for it to match. It's hard to debug exactly what's going on without having the data. Can you confirm that if you use the solr analyzer you can query CompacDiscs on title fine?