ActiveRecord 3“正在”哪里查询
执行 IS IN 查询的最佳方法是什么,尤其是在涉及联接时?
目前,我有类似以下内容:
Table1.joins(:table2).where( { :table2s => { :ident => params[:idents].split(',') } } )
这有效并完成了工作。由此产生的 WHERE 子句就像
WHERE "table2s"."ident" IS IN ('a','b','c')
我觉得这样会更干净:
Table1.joins(:table2).where("table2s.ident IS IN ?", params[:idents]:split(','))
有没有办法避免第一种样式并使用更像第二种样式的东西? (即,where 方法识别数组并使用 IS IN 而不是“=”运算符)
What's the best way to do IS IN queries, especially when involving a join?
Currently, I have something like the following:
Table1.joins(:table2).where( { :table2s => { :ident => params[:idents].split(',') } } )
This works and gets the job done. The resulting WHERE clause is something like
WHERE "table2s"."ident" IS IN ('a','b','c')
I feel like this would be cleaner though:
Table1.joins(:table2).where("table2s.ident IS IN ?", params[:idents]:split(','))
Is there a way to avoid the first style and use something more like the second style? (i.e., the where method recognizes the array and uses IS IN rather than '=' operator)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让查询编译器为您执行此操作通常是更好的方法,因为它可以处理您可能忘记的情况,例如传递
nil
值并最终得到错误的IS IN( NULL)
而不是IS NULL
。不过,您可以清理您的语句:更进一步,您可以将其简化为:
您可以通过编写封装它的作用域来进一步清理它,而不是按原样使用它。
Letting the query compiler do it for you is generally a better way to do it as it will handle cases you might forget, such as passing a
nil
value and ending up with an erroneousIS IN(NULL)
instead ofIS NULL
. You can clean up your statement, though:Taking this a step further, you can reduce it to:
You could further clean this up by writing a scope that encapsulates this instead of using this as-is.
你不需要分裂。 ActiveRecord 足够智能,可以理解数组,因此您只需要
Table1.joins(:table2).where( { :table2s => { :ident => params[:idents]}})
。事实上,你不需要嵌套。
Table1.joins(:table2).where('table2s.ident' => params[:idents])
应该可以找到。阿雷尔真是太聪明了!You don't need the split. ActiveRecord is smart enough to understand arrays, so all you need is
Table1.joins(:table2).where( { :table2s => { :ident => params[:idents]}})
.In fact, you don't need the nesting.
Table1.joins(:table2).where('table2s.ident' => params[:idents])
should work find. Arel is pretty smart!