使用named_scope进行加法链接
有没有办法以附加方式组合范围?
如果我有范围
User.big_haired
,
User.plays_guitar
我可以打电话
User.big_haired.plays_guitar
联系所有留着大头发并弹吉他的用户。 我可以写这个来吸引所有有大头发或弹吉他的用户吗?
我想我必须补充一点,我意识到您可以运行一组查询并将结果添加在一起。 这就是我试图不做的事情。
Is there a way to combine scopes in an additive fashion?
If I have the scopes
User.big_haired
and
User.plays_guitar
I can call
User.big_haired.plays_guitar
and get all the users who have big hair AND play guitar. Can I write this to get all users who have big hair OR play guitar?
I guess I have to add that I realize that you can run a set of queries and add the results together. That's what I'm trying not to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
所以你有:
User.big_haired.plays_guitar => 很多用户。
我不知道有什么方法可以将两者混合在一起。 也许只是混合数组:
So you have:
User.big_haired.plays_guitar => Lots of users.
I am unaware of a method to mash the two together. Perhaps just blending the arrays:
尝试一下Searchlogic,它最近支持使用 OR 组合命名范围
Try Searchlogic, it recently supports combining named scopes with OR
我刚刚在一些定义了named_scopes 的模型上尝试了这一点。 如果您将这些条件组合起来,它会将这些条件组合在一起作为 AND 条件。 所以...
将导致(显然是我的速记 SQL,而不是真正的 Rails 生成的东西)
我不知道如何将它们组合为 OR 关系。 当你考虑各种选择时,混合起来会非常复杂。 我们一直链接named_scopes,它工作得很好(只要你希望它们AND在一起)。
为了执行 and 情况,我要么创建一个带有 OR 条件的特殊命名范围,要么使用联合来生成一个唯一的集合,如下所示:
I just tried this out on some of my models that have named_scopes defined. It will put the conditions together as an AND condition if you combine it. So...
will result in (obviously my shorthand SQL, not the real rails generated stuff)
I don't know of a way to combine them as an OR relationship. That would be incredibly complex to mix in when you think about the various options. We chain named_scopes all the time, it works well (as long as you want them ANDed together).
To do the and case, I would either create a special named scope with the OR conditions built on, or use a union to produce a unique set like so: