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

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.

Related

Rails - Is there a way to autocomplete with form_tag attribute?

My search bar is using a form_tag type, and I can search and enter and it will show results, but it will not give autocompletion or suggestions when typing in the search bar.
When the user starts typing, I want it to display usernames.
Here is what I have tried:
This view is my application.html.erb and it is on my navbar. I dont know if that is also important.
<%= form_tag users_path, :autocomplete => "on", :method => 'get', :id => 'users_search' do %>
<%= text_field_tag :search, params[:search], placeholder:"search members..",style:"width:300px; height:35px;"
%>
<%= submit_tag "", :name => nil, :style => "display: none;" %>
<% end %>
I also tried :autocomplete => :on in the text_field_tag. I'm just not sure how to go about this using form_tag.
Here is the rest of my code that may be important:
User_controller.rb
def index
#users = User.search(params[:search])
end
User.rb
def self.search(username)
if username
username.downcase!
where("username LIKE ?","#{username}%")
else
all
end
end

Rails 5: Two search form_tags on the same page

I'm trying to implement a two search form_tag on a the same page, each search form is placed inside dynamic bootstrap tabs. The first one which is working is basic a search form with one field. The second one which is not working has two fields, one is the same search method as the first and the other I'm trying to get the address from the other_location field and via params[:other_location].
With the current setup the other_location field form the second form does not appear!
Both of the forms are inside partials and I am rendering them inside two dynamic bootstrap tabs like this:
<%= render 'pages/search' %>
<%= render 'pages/search_other' %>
<%= form_tag search_items_path, :method => "get" do %>
<%= text_field_tag :search, params[:search], autofocus: true,
class: "search-query search_size",
placeholder: "Enter product to search" %>
<%= submit_tag "Search", name: nil, :style => "display: none;" %>
<%end%>
<%= form_for :search_other_path, :method => "get" do |form| %>
<%= form.text_field :search, autofocus: true,
class: "search-query search_size",
placeholder: "Enter keyword to search" %>
<% form.fields_for :other_location_path, :method => "get" do |f| %>
<%= f.text_field :other_location, class: "search-query search_size",
placeholder: "Enter address to search" %>
<%= form.submit "Search", name: nil, :style => "display: none;" %>
<%end%>
<%end%>
model
def self.search(search)
return where("0=1") if search !~ /\w{4}/
where("lower(title) LIKE lower(:term)", term: "%#{search}%")
end
routes.rb
get 'search' => 'pages#search', as: 'search_posts'
get 'search' => 'pages#search_other', as: 'search_other'
get 'search' => 'pages#other_location', as: 'other_location'
controller:
def search_other
if params[:search]
#posts = Post.near(other_location,10).search(params[:search]).page(params[:page])
else
#posts = []
end
end
def other_location
other_location = params[:other_location]
if params[:other_location]
Geocoder.search(params[:other_location])
end
end
def search
if params[:search]
#posts = Post.near(action,10).search(params[:search]).page(params[:page])
else
#posts = []
end
end
On your route file:
get 'search/other' => 'pages#search_other', as: 'search_other'
get 'search' => 'pages#search_other', as: 'search_other_items'
both GET requests are going to your pages_controller.rb #search_other method. So even if you have the two form_tags sending the data to different paths (search_other_path, and search_other_items_path) it would be going to the same controler method - which is redundant.
On your actual HTML you have two form tags:
<%= form_tag search_items_path, :method => "get" do %>
and
<%= form_tag search_other_items_path, :method => "get" do %>
You have not mentioned search_items_path in your routes, so I have no idea where that's pointing to. Likely its a proper controller that works since you mentioned the first form was the only one working.
Now, your mentioned controller only has a search method. So to start you are looking at the wrong controller. You should be looking at the controller methods being referenced by the form's action.
In this case, the second form is sending it's request to search_other_items_path which according to your routes, its pointing to pages_controller.rb -> #search_other method.
You should edit your question to include code that is actually relevant. Maybe then I can actually help.

Build static dropdown menu for simple search Rails 3

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

update_attributes with none-standard form

I have cobbled together a form due to some oddities in my code and routes. Things work for adding data to the database, but I can't quite seem to figure out how to update data. Here is some code.
new.html.erb
<% form_tag '/list' do %>
Episodes Completed:
<%= text_field_tag "completed" %>
Watch Status
<%= collection_select(nil, 'id', #show_status, :id, :state) %>
<%= hidden_field_tag('show_id', #show.id) %>
<%= submit_tag 'Add' %>
<% end %>
edit.html.erb
<% form_tag("/list/#{#show_completion.show.id}", :method => :put ) do %>
Episodes Completed:
<%= text_field_tag "completed", #show_completion.episodes_completed %>
Watch Status
<%= collection_select(nil, 'id', #show_status, :id, :state) %>
<%= hidden_field_tag('show_id', #show_completion.show.id) %>
<%= submit_tag 'Edit' %>
<% end %>
Here is the controller's Create and Update methods
def create
#show_completetion = ShowCompletionStatus.new
#show_completetion.user_id = current_user.id
#show_completetion.episodes_completed = params[:completed]
#show_completetion.status_state_id = params[:id]
#show_completetion.show_id = params[:show_id]
#show_completetion.save
end
def update
#show_completion = ShowCompletionStatus.find(params[:id])
#show_completion.episodes_completed = params[:completed]
#show_completion.status_state_id = params[:id]
#show_completion.show_id = params[:show_id]
if #show_completion.update_attribute('episodes_completed', params[:completed])
redirect_to "/list/#{current_user.username}"
else
redirect_to "/list/#{params[:id]}/edit"
end
end
Here are my routes for these:
match "list/" => "list#create", :via => :post
match "list/new/:show_id" => "list#new", :constraints => { :show_id => /[0-9]+/ }
match "list/:id/edit" => "list#edit", :constraints => { :id => /[0-9]+/ }, :via => :get
match "list/:id" => "list#update", :constraints => { :id => /[0-9]+/ }, :via => :put
I have been trying different things to get this to work for the better part of 4 hours now. I think I am just missing something, but I just can't see it.
Is there a better way to do the form that makes it work better?
Any help is appreciated.
I solved this issue by making a hash and passing it to the update attributes with the key value pairs of what the objects attributes would be. Since updates_attributes takes a hash and not an object it was a simple solution once the connection was made.
Try to replace your update_attribute call for a save call.
Also, if you're writing everything from scratch instead of using the builtins, try to use save! instead of save: it will raise an exception if it fails, unlike the plain save that just returns false.

Rails - Using Autocomplete with the Scoped_search gem?

I'm using the scoped_search gem for basic search functionality on my site. Scoped search: http://github.com/wvanbergen/scoped_search
I'm using the most basic possible implementation of this gem. I'm searching on the name attribute in a user model only. On the frontend, in users/index, the search input is a text_field_tag.
<% form_tag users_path, :method => :get do %>
<%= text_field_tag :search, params[:search], :value => 'Search' %>
<%= submit_tag "Go", :name => nil %>
<%end%>
In the user model, I have:
scoped_search :on => :name
I want to implement basic auto-complete functionality on the user model, name attribute. This would be the most basic use case if I was searching in a form element of the user model, but the scoped_search part is throwing me off.
I was planning to use DHH's auto_complete plugin, but I'm open to using whatever tool helps me accomplish this.
Auto-complete: http://github.com/rails/auto_complete
Thanks.
In the model you should replace the
line:
scoped_search :on => :name
with:
scoped_search :on => :name, :complete_value => true
In the view replace the line:
<%= text_field_tag :search, params[:search], :value => 'Search' %>
with:
<%= auto_complete_field_tag_jquery(:search, params[:search], {},{}) %>
In the controller you should add the following method:
def auto_complete_search
#items = User.complete_for(params[:search])
render :json => #items
end
did you see the demo app at https://github.com/abenari/scoped_search_demo_app ?
Alternatively, you can see how I use it in my project - https://github.com/ohadlevy/foreman
Ohad

Resources