【发布时间】:2011-03-17 03:02:45
【问题描述】:
我正在尝试根据可选的导轨链接标准 参数。
我希望能够同时根据所选标签进行过滤 以及搜索。
这是适用于所有情况的当前代码:
if params[:tag] and params[:search]
@notes = Note.tagged_with_criteria(params[:tag]).full_text_search(params[:search])
elsif params[:tag]
@notes = Note.tagged_with_criteria(params[:tag])
elsif params[:search]
@notes = Note.full_text_search(params[:search])
end
我尝试简单地使用
@notes = Note.tagged_with_criteria(params[:tag]).full_text_search(params[:search])
没有 if 语句,但是如果只有一个参数是 给定,则返回所有音符。
每种方法(tagged_with_criteria 和 full_text_search)都是 如果参数为 nil / 为空,则返回 Note.criteria。
有没有更简单、更优雅的方式来像这样链接 Mongoid 标准?
我宁愿继续逐一跟踪标准,而不是不得不做 奇怪的“if params[...] and params[...]”的事情..
更新:以下是当前的方法:
def tagged_with_criteria(_tags)
_tags = [_tags] unless _tags.is_a? Array
if _tags.empty?
criteria
else
criteria.in(:tags => _tags)
end
end
def self.full_text_search(query)
if query
begin
regex = /#{query}/
# supplied string is valid regex (without the forward slashes) - use it as such
criteria.where(:content => regex)
rescue
# not a valid regexp -treat as literal search string
criteria.where(:content => (/#{Regexp.escape(query)}/))
end
else
# show all notes if there's no search parameter
criteria
end
end
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 mongodb mongoid