I set up a search mechanism for my Procedure table following this railscast http://railscasts.com/episodes/37-simple-search-form?autoplay=true. I pretty much followed it exactly but I get this error when I submit the search:
ActiveRecord::RecordNotFound at /procedures
Couldn't find all Procedures with 'id': (all, {:conditions=>["name LIKE ?", "%Emergency%"]}) (found 0 results, but was looking for 2)
I want to search for Procedures by name, and this error makes it look like it is searching by id?
Here is the view:
<%= form_tag procedures_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search], :id => "welcome-search" %>
<%= submit_tag "Search Procedures", :name => nil, :class => "btn btn-success btn-lg" %>
My controller:
def index
#procedures = Procedure.search(params[:search])
render `procedures/index`
end
My model:
def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
I'm pretty confused since the railscast makes it look so easy to get working..Thanks.
find(:all) is very old and is no longer available since rails 3.2. Instead use where:
def self.search(search)
if search
where('name LIKE ?', "%#{search}%")
else
all
end
end
Related
I am creating a rails app where I have implemented the following search function.
application.html.erb
<div class="searchbar">
<%= form_tag(articles_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: " Search", :class => "search_form" %>
<%= submit_tag "Search", :name => nil %>
<% end %>
</div>
article.rb
def self.search(search)
where("title LIKE ? OR creator LIKE ? OR description LIKE ?", "%#{search}%", "%#{search}%", "%#{search}%")
end
articles_controller.rb
def index
#articles = Article.all
if params[:search]
#articles = Article.search(params[:search]).order("created_at DESC")
else
#articles = Article.all.order("created_at DESC")
end
end
This allows me to search for all primary resources but does not include nested resources in the search results. Is there a way to include these resources within the same function?
You'd need to do some joins, and define a syntax for passing the relevant join info into your search method.
This can get complicated pretty quick, and I'd highly suggest you don't reinvent the wheel and use an existing solution such as ransack. This will let you do things like
Article.ransack(title_cont: "code", author_name_cont: "bob").result
where, in this example, Author is its own model, associated with Article, and containing the field name.
It also plays very nice with views and forms, so you can very easily implement search forms without having the manually key everything up to the right association and field.
(Personally I'm not in love with their concatenation syntax but it gets the job done.)
I want to be able to search and update the index.
this is my controller method:
def index
if params[:search]
#ofertas = Oferta.search(params[:search]).paginate(page: params[:ofertas_page], :per_page => 5)
else
#ofertas = Oferta.all.paginate(page: params[:ofertas_page], :per_page => 5)
end
end
My search method in the model
def self.search(search)
where("titulo like ?","%w{search}%")
end
and this is the search form
<%= form_tag ofertas_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search], placeholder: "Procurar Entidades" %>
<%= submit_tag "Procurar", :name => nil %>
</p>
<% end %>
I've seen this setup in a number of search tutorials but no matter what I type nothing appears. Does someone know what I'm doing wrong?
It looks like you were trying to interpolate the search variable into the string, but didn't quite get the right symbol. How about this:
"%#{search}%"
Note the # instead of the w.
where("titulo like ?","%w{search}%")
should be:
where("titulo like ?", "%#{search}%")
#{xxx} is for string interpolation - it allows you to inject ruby (including variables) into a string.
"%xxxx%" is telling SQL that the search string can appear anywhere in the titulo column. '%' is a wildcard in SQL.
%w{xxx yyy zzz} is shorthand for ["xxx", "yyy", "zzz"] - an array in Ruby, which wouldn't mean much to the SQL as a string by itself.
I am working on a search function in Rails. I followed the following tutorial
http://railscasts.com/episodes/37-simple-search-form
I have therefore updated my tutorial.rb with the following
def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
Updating my tutorials_controller.rb with the following
def index
#tutorials = Tutorial.search(params[:search])
end
Finally my view with
<div id="search">
<%= form_tag tutorials_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil, :class => "btn btn-success" %>
</p>
<% end %>
</div>
So it is all displaying. When I hit the search box I get the following error.
ActiveRecord::StatementInvalid in TutorialsController#index
SQLite3::SQLException: no such column: name: SELECT "tutorials".* FROM "tutorials" WHERE (name LIKE '%%')
Any help greatly appreciated. Still new to this and a little our of my depth. I can see that it is having problem getting information from the database but not sure how to cure it.
Cheers!
As per the error SQLite3::SQLException: no such column: name,
there is no column name in the tutorials table.
If you intended to search the tutorials table based on name field then add it to the tutorials table with a migration:
rails g migration AddNameToTutorial name
run rake db:migrate
Insert some records in Tutorial table with names.
Then, go ahead and search based on name field in tutorials table with your current code.
Second option is, if you intended to search tutorials table based on some other existing field then just update the search method as below:
def self.search(search)
if search
find(:all, :conditions => ['fieldname LIKE ?', "%#{search}%"])
else
find(:all)
end
end
where replace fieldname with the attribute name that you want to search on.
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
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.