1

I have defined two scope-like methods on a model:

def self.foo var
  where(foo: var)
end

def self.bar var
  where(bar: var)
end

I want to be able to pass nil to one of these methods and have it effectively be ignored. So:

var1 = 10
var2 = nil
# ...
Model.foo(var1).bar(var2)

I've tried various things such as:

def self.bar var
  return self if var.nil?
  where(bar: var)
end

but in the above instance, self doesn't return what this method has been passed from the previous method in the chain, it returns Model, therefore I lose all the legwork done in foo.

How can I achieve what I'm trying?

4

2 回答 2

1

all将实际运行查询而不是返回一个ActiveRelation对象,该对象用于在查询实际需要返回结果时(例如:当您实际运行时each)延迟加载查询。否则,它根本不执行查询,为您节省了对数据库的调用。它还允许您基本上在这里尝试实现的良好链接。

你可能想尝试的是

def self.bar(val)
  return where({}) if val.nil?
  where(:bar => val)
end
于 2013-02-07T16:03:27.587 回答
1

我相信rails 3.x,你应该能够使用这样的东西:

return self.scoped if var.nil?

在 rails 4.x 中,您需要将其更改为:

return self.all if var.nil?

基本上,'scoped'(和 rails 4 中的'all')返回一个关系对象,您可以将其与其他 arel 方法链接起来,而无需实际对其应用任何条件。

于 2013-02-07T15:49:32.707 回答