有没有办法将命名范围组合成新的命名范围?
我有
class Foo < ActiveRecord::Base
named_scope :a, lambda { |a| :conditions => { :a => a } }
named_scope :b, lambda { |b| :conditions => { :b => b } }
end
我想要的,
class Foo < ActiveRecord::Base
named_scope :ab, lambda { |a,b| :conditions => { :a => a, :b => b } }
end
但我更喜欢以干的方式来做。 我可以通过使用获得相同的效果
Foo.a(something).b(something_else)
,但它不是特别可爱。
I have
class Foo < ActiveRecord::Base
named_scope :a, lambda { |a| :conditions => { :a => a } }
named_scope :b, lambda { |b| :conditions => { :b => b } }
end
I'd like
class Foo < ActiveRecord::Base
named_scope :ab, lambda { |a,b| :conditions => { :a => a, :b => b } }
end
but I'd prefer to do it in a DRY fashion. I can get the same effect by using
Foo.a(something).b(something_else)
but it's not particularly lovely.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是重用named_scope来定义另一个named_scope
我为了方便起见,将其复制到此处:
您可以使用 proxy_options 将一个named_scope回收到另一个named_scope中:
这样它就可以与其他named_scope链接。
我在我的代码中使用了它并且它运行得很好。
我希望它有帮助。
Yes Reusing named_scope to define another named_scope
I copy it here for your convenience:
You can use proxy_options to recycle one named_scope into another:
This way it can be chained with other named_scopes.
I use this in my code and it works perfectly.
I hope it helps.
@PJ:你知道,我曾考虑过这一点,但放弃了它,因为我认为我以后无法链接到第三命名范围,如下所示:
但是自从
ab(x , y)
返回 b(y) 将返回的任何内容,我认为该链可以工作。 让我重新思考显而易见的事情!@PJ: you know, I had considered that, but dismissed it because I thought I wouldn't be able to later chain on a third named scope, like so:
But since
ab(x, y)
returns whateverb(y)
would return, I think the chain would work. Way to make me rethink the obvious!好吧,我对 Rails 还很陌生,我不确定你到底要做什么,但如果你只是为了代码重用,为什么不使用常规的类方法呢?
您可以通过采用 *args 而不是 a 和 b 来使其更加灵活,然后可以将其中之一设为可选。 如果你陷入了named_scope,你不能扩展它来做同样的事情吗?
如果我完全不同意你想做的事情,请告诉我。
Well I'm still new to rails and I'm not sure exactly what you're going for here, but if you're just going for code reuse why not use a regular class method?
You could make that more flexible by taking *args instead of a and b, and then possibly make one or the other optional. If you're stuck on named_scope, can't you extend it to do much the same thing?
Let me know if I'm totally off base with what you're wanting to do.
通过使其成为类方法,您将无法将其链接到关联代理,例如:
另一种方法是应用 此补丁 为named_scope启用 :through 选项:
By making it a class method you won't be able to chain it to an association proxy, like:
An alternative is applying this patch to enable a :through option for named_scope:
至少从 3.2 开始有一个聪明的解决方案:
At least since 3.2 there is a clever solution :
查看:
http://github.com/binarylogic/searchlogic
令人印象深刻!
再具体一点:
Check out:
http://github.com/binarylogic/searchlogic
Impressive!
To be specific: