Pergunta

I have very large database and I'm use an advanced search form similar to this railscast: http://railscasts.com/episodes/111-advanced-search-form-revised

Perhaps it's a dumb question but imagine that you have 400,000 products (or more) that you are filtering with this chain of .where (and pagination).

products = Product.order(:name)
products = products.where("name like ?", "%#{keywords}%") if keywords.present?
products = products.where(category_id: category_id) if category_id.present?
products = products.where("price >= ?", min_price) if min_price.present?
products = products.where("price <= ?", max_price) if max_price.present?
products.page(params[:page])

As I see it the search executes the first condition, and then filters with the other where conditions so you'd have 400,000 products searched. Would that not kill performance, or am I totally (I wish) wrong?

Note: I also wrote asked this question on the railscast but, being an old railscasts, I don't know if anybody will see the question there. For that reason I wrote here too.

Foi útil?

Solução

just use an Hash from the parameters that comes from the form, it's been a while since I've done and it and I dont even have the code anymore but in theory it should be like:

finder = Hash.new
params[:form].each {|index, val|
finder[index] = val
}

that will create an Hash of all the parameters that have been passed and you can just pass that to the active record search like this.

products = Products.where(finder)

Outras dicas

Rails will compose all those .where conditions into one SQL query.

If your database is correctly indexed then you should be OK.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top