Build static dropdown menu for simple search Rails 3 - ruby-on-rails

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

Related

How to call method via hyperlink?

How can I call a method with a hyperlink on my index.html.erb?
I currently have a search field that allows the user to type in a keyword. This will search attributes in a model and display any that are found.
For example, I have records_controller.rb with this in it:
def index
#records = Record.search(params[:search])
end
app/models/record.rb has:
# Added for the search
def self.search(search)
where("title LIKE ? OR keyword LIKE ? OR description LIKE ?", "%#{search}%", "%#{search}%", "%#{search}%")
end
'title, 'keyword', and 'decscription' are attributes in the model.
app/views/records/index.html.erb contains a search form:
<%= form_tag(records_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: " Search" %>
<%= submit_tag "Find" %>
<% end %>
On this same index.html.erb page, how can I add a hyperlink that displays all data from a model that contains a title I specify?
Such as displaying all rows that have the title "truck".
If the user clicks the hyperlink, it will display data
where('title LIKE "truck"', "%#{search}%")
I'm assuming I'll also need to put a new method in the record model such as:
# I'll have to play with this because I know it is wrong
# Added for the search
def self.searchtruck(search)
where('title LIKE "truck"', "%#{search}%")
end
This does what you're asking, creates a link with the param[:search] = 'truck'
<%= link_to 'Search for truck', records_path(search: 'truck') %>

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..." %>

Generate search results for users by city in Rails 4

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.

Sunspot Rails - Can user change what fields to search?

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

how to get simple search in rails based on RailsCasts tutorial?

I followed the RailsCasts tutorial to do a simple search with autocomplete, but it doesn't work. :(
view/vendors/index:
<% form_tag vendors_path, :method => 'get' do %>
<%= text_field_with_auto_complete :vendor,
:name,
{},
{:method => :get, :class => 'textbox'} %>
<%= submit_tag "Search", :name => nil %>
<% end %>
</div>
<%= #searchvendor.id %>
<%= #searchterm %>
I included #searchterm and #searchvendor.id as validation steps.
So this should call the controller => vendor, action=> index:
def index
#searchterm = params[:vendor][:name]
#searchvendor = Vendor.search('checkpoint')
And the search method is created as follows for the vendor/model:
def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
The output?
#searchterm does show the value that is inputed as that shows up in the URL as vendor[name]=?
#searchvendor.id is a long string and #searchvendor.name shows an error, name not a method.
I'm stumped. Help...please?
LINK to the Tutorial:
http://railscasts.com/episodes/37-simple-search-form
Should you not be passing in your #searchterm into your Vendor.search method? Passing 'checkpoint' each time probably isn't going to do the trick.
#searchvendor is going to contain an Array as you are doing find(:all). You'll need to iterate over the array and do .name on each item.

Resources