Finnjon
Finnjon

Reputation: 671

How can I query a rails 3 app efficiently?

I have a search form that queries one table in the database but there are many parameters (language, level, creator etc). The code below works provided the fields in question are filled in but I want to change it to:

a) add more parameters (there are several); b) allow for a field to be empty

Here's the code in the controller:

@materials = Material.find(:all, :conditions => {:targ_lang => params["targ_lang"],
                                                 :inst_lang => params["inst_lang"],
                                                 :level => params["level"]})

Totally new to this I'm afraid but a lot of the documentation suggests I should be using "where".

Upvotes: 0

Views: 66

Answers (2)

Silver
Silver

Reputation: 693

Since Rails 3 you can use the where() function:

@materials = Material.where(targ_lang: params["targ_lang"], inst_lang: params["inst_lang"], level: params["level"])

Also, you could take a look at scopes

These allow you to set what you want to do in the model and call it in the controller for example:

class Material < ActiveRecord::Base
  scope :active, where(active_state: true)
end

Then in the controller you do something like:

@active_materials = Material.active

This can be useful if you are joining several models and want to keep your controllers less messy.

To conclude, like @RVG said, seachlogic is quite useful as well as, there are others like Sphinx and Elastic Search. You should take a quick look at these and use the one you feel most confortable with.

Upvotes: 2

Raghuveer
Raghuveer

Reputation: 2636

If you are using search functionality in your app I suggest using SearchLogic gem

It is easy to use and effective..

SearchLogic

RailsCasts for searchlogic

Upvotes: 1

Related Questions