Thanks to people on this list, I was able to implement a search across columns (thank you guys!) However, I am not sure if I did it the right way.
What I did is that on the view page, I have implemented the search as follows:
<% form_tag books_path, :method => 'get' do %> <p> <%= text_field_tag :search, params[:search] %> <%= select_tag(:fieldname,options_for_select(Book.column_names.reject{|x| x == 'id' || x.match(/(_id\Z|_at\Z)/)})) %> <%= submit_tag "Search" %> </p> <% end %>
The controller I setup as follows:
class BooksController < ApplicationController
def index
@books =Book.search(params[:search], params[:page], params[:fieldname])
respond_to do |format| format.html # index.html.erb format.xml { render :xml => @books } end end
end
And the model:
def self.search(search, page, fieldname) if fieldname.nil? paginate :per_page => 20, :page => page, :conditions => ['name like ?', "%#{search}%"], :order => 'name' else paginate :per_page => 20, :page => page, :conditions => ["#{fieldname} like ?", "%#{search}%"], :order => 'name' end end
It seems to work for me, but I can't get rid of the nagging feeling that I am not doing something right and I think its has to do with the model. Is it safe to pass column names like that?
Also, there is some duplication across all the controllers for the index search - should I just try consolidate all of that into the application controller (I am not sure how I can redefine the model name if consolidation is necessary, but that I can search for and figure out for a while).
Finally, if this isn't right/or proper way, is there another way that is better? I know a bit about the searches based on model and/or named scopes (by way of railscasts) - are those the recommended way in general in the Rails community (aside from an index daemon like Sphinx* which I may end up using anyway in the future).
*If you are wondering why I don't want to use Sphinx, its mostly because I want to be prepared in case I am in the situation where I can't put in Sphinx or any other search daemon and I have to rely on searching by this method instead.
- Rilindo