使用named_scope进行加法链接

发布于 2024-07-30 15:11:10 字数 317 浏览 3 评论 0原文

有没有办法以附加方式组合范围?

如果我有范围

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雾里花 2024-08-06 15:11:10

所以你有:

class User < ActiveRecord::Base
  named_scope :big_haired, :conditions => {:hair => 'massive'}
  named_scope :plays_guitar, :conditions => {:plays => 'guitar'}
end

User.big_haired.plays_guitar => 很多用户。

我不知道有什么方法可以将两者混合在一起。 也许只是混合数组:

@users = (User.big_haired + User.plays_guitar).uniq

So you have:

class User < ActiveRecord::Base
  named_scope :big_haired, :conditions => {:hair => 'massive'}
  named_scope :plays_guitar, :conditions => {:plays => 'guitar'}
end

User.big_haired.plays_guitar => Lots of users.

I am unaware of a method to mash the two together. Perhaps just blending the arrays:

@users = (User.big_haired + User.plays_guitar).uniq
不乱于心 2024-08-06 15:11:10

尝试一下Searchlogic,它最近支持使用 OR 组合命名范围

Try Searchlogic, it recently supports combining named scopes with OR

浪菊怪哟 2024-08-06 15:11:10

我刚刚在一些定义了named_scopes 的模型上尝试了这一点。 如果您将这些条件组合起来,它会将这些条件组合在一起作为 AND 条件。 所以...

User.big_haired.plays_guitar

将导致(显然是我的速记 SQL,而不是真正的 Rails 生成的东西)

SELECT * FROM users WHERE hair = 'massive' AND plays = 'guitar'

我不知道如何将它们组合为 OR 关系。 当你考虑各种选择时,混合起来会非常复杂。 我们一直链接named_scopes,它工作得很好(只要你希望它们AND在一起)。

为了执行 and 情况,我要么创建一个带有 OR 条件的特殊命名范围,要么使用联合来生成一个唯一的集合,如下所示:

User.big_haired | User.plays_guitar

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...

User.big_haired.plays_guitar

will result in (obviously my shorthand SQL, not the real rails generated stuff)

SELECT * FROM users WHERE hair = 'massive' AND plays = 'guitar'

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:

User.big_haired | User.plays_guitar
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文