Rails,如何将示波器与"and"链接?他们之间的运算符? [英] Rails, how do I chain scopes with an "and" operator between them?

查看:128
本文介绍了Rails,如何将示波器与"and"链接?他们之间的运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的示波器:

I have a scope that look like this:

scope :attr_similar_to, -> (attr, strings) { where("#{attr} similar to ?", "%(#{strings})%") }

我使用此范围的方式是遍历多个属性,对于每个属性,我将属性连同字符串"变量中的一组多个字符串一起发送到范围中,这些变量以"foo | bar | etc".因此,对于每个属性,我都会检查属性值是否与任何字符串相似.

The way I use this scope is that iterate through a number of attributes and for each attribute I send the attribute into the scope along with a set of multiple strings in the 'strings' variable, which gets sent into this scope as "foo|bar|etc". So for each attribute, I check if the attribute value is similar to any of the strings.

我使用此范围的循环如下:

The loop where I use this scope looks like this:

results = Model.none
attributes.each do |attr|
  results += attr_similar_to(attr, strings)
end

问题是,如果我有两个属性名称"和年龄",并且只有名称"在"foo"上匹配,它将仍然获取所有与"foo"匹配的记录.我希望能够将这些范围调用与诸如"and"运算符之类的链接在一起,以便例如"name"和"age"都必须匹配,才能获取任何记录.

The problem is that if I have two attributes, "name" and "age", and only "name" matches on "foo", it will still fetch me all those records matching with "foo". I want to be able to chain these scope calls with something like an "and" operator between them so that for example both "name" and "age" must get a match each in order to fetch me any records.

我可能是想以一种错误或低效的方式来做到这一点吗?

Am I perhaps trying to do this in a wrong or inefficient way?

推荐答案

results = Model.all    # Model.scoped in rails 3

attributes.each do |attr|
  results = results.attr_similar_to(attr, strings)
end

或更简洁:

results = attributes.inject(Model.all) do |result, attr| 
  result.attr_similar_to(attr, strings)
end

这篇关于Rails,如何将示波器与"and"链接?他们之间的运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆