Is there a better way to write this named_scope? [Rails]
I am using this named_scope to search for products that have a description matching any word the user inputs.
E.g., Product.description_like_any("choc pret")
Will return products with names like
- "Chocolate Bar"
- "Chocolate Covered Pretzels"
- "Miniature Chocolate Ponies"
Here's the named_scope I've written (which works)
named_scope :description_like_any, (lambda do |query|
return {} unless query
conditions = []
values = []
for q in query.split(/\s+/)
conditions << "(`products`.description LIKE ?)"
values << "%#{q}%"
end
{ :conditions => [conditions.join(' AND '), *values] }
end)
Is there a better way to write this? Perhaps I'm missing a Rubyism/Railism or two?
Solution
Using scope_procedure
in conjunction with Searchlogic, this can be done in an even easier way. Note, the solution before even leverages Searchlogic's _or_
syntax for connecting two scopes together. The :keywords
开发者_StackOverflowscope_procedure finds products matching product.description
, or product.vendor.name
; All with one text field!
Model
# app/models/product.rb
class Product < ActiveRecord::Base
scope_procedure :keywords, lambda |query|
description_like_any_or_vendor_name_like_any(query.split(/\s+/))
end
end
Controller
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
def index
@search = Product.search(params[:search])
@products = @search.all
end
end
Views
# app/views/products/index.html.erb
<% form_for @search do |f| %>
<%= f.label :keywords, "Quick Search" %>
<%= f.input :keywords %>
<%= f.submit, "Go" %>
<% end %>
The most Railsy thing to do is to not write this yourself. :-) Use the excellent Searchlogic gem which will create the description_like_any
scope for you.
Edit: If you want your user to be able to enter search terms in a free text field like this, you can define your own scope:
class Product < ActiveRecord::Base
# ...
scope_procedure :description_like_any_term, lambda { |terms|
name_like_any(terms.split(/\s+/))
}
# ...
end
精彩评论