Shiv Aggarwal
Shiv Aggarwal

Reputation: 499

rails modle base search with check boxes

I am working on search functionality in rails and I want a common search method for all the site. For that I am creating a method in app controller with two parameters one is modleName and another one is fieldsArray. but am not able to make it. Please help me.

I want that I set a variable in model that on which columns I need a search as like (attr_accessible) and then I need a element which I call in view files and it gets all the columns with labels and check boxes which I set in model. and I get a result with the specific column name which I enter in search box and which columns I have selected, columns would be multiple selected.

Please help.

Thanks

Upvotes: 0

Views: 49

Answers (1)

Pramod Solanky
Pramod Solanky

Reputation: 1690

Hope this helps:

Create a utility class which has your generic search method.

class Util
  # modelName is a string, fields would be an array of strings, keyword is string as well
  # You could either call fire search from here or from individual models

  def search(modelName, fields, keyword)
    query = ""
    fields.size.each_with_index do |field, index|
      query += "#{field} like #{keyword} "
      query += " OR " if index < fields.size
    end

    modelName.constantize.where(query)
    # Or create search method in all ur models which you want to search and 
    modelName.constantize.search(fields, keyword)

   end
 end

I haven't included the model search methods as its self explanatory as to what the method should look like.

Let me know if this helps

Upvotes: 1

Related Questions