Rails:使用 or 条件进行 searchlogic 搜索

发布于 2024-08-10 17:00:23 字数 1193 浏览 3 评论 0原文

我在版本 2.3.5 中使用“binarylogic-searchlogic”gem 以及 Rails 2.3.4。

我想要做的是在模型上搜索多个属性的指定值。我通过将所有内容链接在一起来实现这一点,例如

User.first_name_or_last_name_or_email_like(value)

但是随着搜索中属性越来越多,这往往会很丑陋。相反,我想使用这样的 searchlogic 搜索机制:

search = User.search
search.first_name_like = value
search.last_name_like  = value
..
@users = search.all

所以这是通过 AND 搜索的方式 - 但我想要的是 OR。我找到了两种方法来实现这一目标,但都不起作用。

第一个:在条件前添加一个 or_

search = User.search
search.first_name_like = value
search.or_last_name_like  = value
@users = search.all

这给了我 The or_last_name_like 不是一个有效的条件。您只能使用映射到命名范围的条件

第二个:使用search.any

search = User.search
search.first_name_like = value
search.last_name_like  = value
@users = search.any

为我提供未定义的方法any' for #`。

有什么想法吗?我是否错过了自述文件的正确观点?

感谢您非常欢迎的帮助!

编辑:是时候采取一些丑陋的解决方法了:

search = User.search
search.first_name_like = value
search.last_name_like  = value
User.find(:all, :conditions => search.scope(:find).gsub('AND','OR'))

有效,但肯定不是可行的方法,不是吗?

I'm using the 'binarylogic-searchlogic' gem in version 2.3.5 along with Rails 2.3.4.

What I want to do is performing a search on a model for a specified value over multiple attributes. I achieve this through chaining everything together like

User.first_name_or_last_name_or_email_like(value)

But with more and more attributes in this search this tends to be ugly. Instead I'd like to use the search mechanism of searchlogic like this:

search = User.search
search.first_name_like = value
search.last_name_like  = value
..
@users = search.all

So this is the way to search via AND - but what I want is OR. I've found two ways to achieve this, but both don't work.

1st one: prepend an or_ to the condition

search = User.search
search.first_name_like = value
search.or_last_name_like  = value
@users = search.all

This gives me The or_last_name_like is not a valid condition. You may only use conditions that map to a named scope

2nd one: use search.any

search = User.search
search.first_name_like = value
search.last_name_like  = value
@users = search.any

gives me undefined methodany' for #`.

Any idea's on that? Am I mising the right point of the readme?

Thanks for your very welcome help!

edit: time for some ugly workaround:

search = User.search
search.first_name_like = value
search.last_name_like  = value
User.find(:all, :conditions => search.scope(:find).gsub('AND','OR'))

Works but is surely not the way to go, isn't it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

浅笑依然 2024-08-17 17:00:23

我不认为还有其他方法可以做到这一点。默认情况下,它将使用 AND 连接参数。

OR 代码似乎只适用于链接。

I don't think there's another way of doing it. By default it will join the arguments with AND.

The OR code, only seems to work with chaining.

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