有没有更好的方法来编写named_scope?[路轨] [英] Is there a better way to write this named_scope? [Rails]
问题描述
我正在使用named_scope搜索具有与用户输入的任何单词相匹配的描述的产品.
I am using this named_scope to search for products that have a description matching any word the user inputs.
例如, Product.description_like_any("choc pret")
将退回具有类似名称的产品
Will return products with names like
- 巧克力棒"
- 巧克力脆饼干"
- 迷你巧克力小马"
这是我写的named_scope(有效)
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)
有没有更好的方法来编写此代码?也许我缺少一两个Rubyism/Railism?
Is there a better way to write this? Perhaps I'm missing a Rubyism/Railism or two?
将 scope_procedure
与Searchlogic结合使用,可以更轻松地完成此操作.请注意,之前的解决方案甚至利用Searchlogic的 _or _
语法将两个范围连接在一起.:keywords
scope_procedure查找与 product.description
或 product.vendor.name
;匹配的产品.全部只有一个文本字段!
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
scope_procedure finds products matching product.description
, or product.vendor.name
; All with one text field!
# 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
控制器
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
def index
@search = Product.search(params[:search])
@products = @search.all
end
end
观看次数
# app/views/products/index.html.erb
<% form_for @search do |f| %>
<%= f.label :keywords, "Quick Search" %>
<%= f.input :keywords %>
<%= f.submit, "Go" %>
<% end %>
推荐答案
最具讽刺意味的是,不要自己写这篇文章.:-)使用出色的 Searchlogic 宝石,它将为以下对象创建 description_like_any
范围你.
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.
如果希望用户能够在这样的自由文本字段中输入搜索字词,则可以定义自己的范围:
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
这篇关于有没有更好的方法来编写named_scope?[路轨]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!