我可以使用 AREL/ActiveRecord 更优雅地编写此查询吗?
我可以使用 AREL/ActiveRecord API 将该查询编写得更短和/或更优雅吗?
Foo.where("(bar is not null and bar != '') or (baz is not null and baz !='')")
Can I write this query shorter and/or more elegantly using the AREL/ActiveRecord API?
Foo.where("(bar is not null and bar != '') or (baz is not null and baz !='')")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以直接使用 Arel 执行
OR
运算符,但语法不是很漂亮,并且可能有点难以阅读。这是它在 arel 中的样子:我建议看看 squeel gem。它使您可以访问活动记录中的更多功能。您的查询如下:
以下是更多信息的链接:http://erniemiller.org/projects/squeel/
您可以通过几种不同的方式在 squeel 中编写它,它支持几种不同的语法样式,因此如果您不喜欢上面的样式,还有其他选择。
You can do an
OR
operator with Arel directly but the syntax isn't hugely pretty and can get a bit hard to read. Here is what it would look like in arel:I'd suggest looking at the squeel gem. It gives you access to more arel functionality in active record. Your query would like like:
Here is the link for more info: http://erniemiller.org/projects/squeel/
There are a few different ways you can write that in squeel, it supports a few different syntax styles so if you don't liked the one above there are alternatives.
处理这个问题的明智方法(如果您有权限当然可以在数据库上执行此操作)是不允许数据库中存在空字符串值。然后你可以执行 Foo.where(:bar => nil)。我使用 attribute_normalizer 来实现此目的,并正确格式化值。
https://github.com/mdeering/attribute_normalizer
快速搜索也显示了 nilify 空白,但我还没有我尝试过,因为属性规范化器已经为我提供了该功能。
https://github.com/rubiety/nilify_blanks
如果您有保存良好的数据库(空字段的空字符串值或空字符串值可能尽可能短。(我自己更喜欢空字符串)。
The sane way to deal with this (if you have the rights do do this of course on the database) is to disallow empty string values in the database. Then you can do Foo.where(:bar => nil). I use attribute_normalizer for this, and also to format values correctly.
https://github.com/mdeering/attribute_normalizer
A quick search also reveals nilify blanks, but I haven't tried that because attribute normalizer already provides that functionality for me.
https://github.com/rubiety/nilify_blanks
The resulting sql for the search you want if you have a well kept database (either null or empty string values for empty fields is probably as short as it gets. (I prefer empty strings myself).