Rails, how do I chain scopes with an “and” operator between them?

非 Y 不嫁゛ 提交于 2019-12-12 02:04:04

问题


I have a scope that look like this:

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

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

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?


回答1:


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

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

Or more concise:

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


来源:https://stackoverflow.com/questions/26483569/rails-how-do-i-chain-scopes-with-an-and-operator-between-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!