Rails:使用 or 条件进行 searchlogic 搜索
我在版本 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 method
any' 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不认为还有其他方法可以做到这一点。默认情况下,它将使用 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.