在 Rails 3 中是否有一种与数据库更加无关的方法来编写这个默认范围?
我在我的模型之一中定义了以下默认范围
default_scope order("IF(format = #{FORMATS[:wide]}, 1, 0) DESC, created_at DESC, name ASC")
,它在我运行 MySQL 的开发机器上运行良好,但在部署到我们使用 postgres 的生产环境中时就出现了问题。有没有办法使用 Arel 而不是直接 SQL 来编写它? FORMATS[:wide]
返回一个整数,但它可能不按任何特定顺序。我只想首先返回具有特定格式
的记录。
I have the following default scope defined in one of my models
default_scope order("IF(format = #{FORMATS[:wide]}, 1, 0) DESC, created_at DESC, name ASC")
It worked fine on my dev machine where I'm running MySQL, but borked when deployed to production where we use postgres. Is there a way to write that using Arel instead of straight SQL? FORMATS[:wide]
returns an integer, but it may not be in any particular order. I just want records with that particular format
to be returned first.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我根本不会把它放在 SQL 中。我可能会为每种格式类型制定一个范围,然后使用 Ruby 来确定使用哪种格式。或者创建一个方法来确定排序顺序并将其传递到您使用它的任何地方。
I wouldn't put that in SQL at all. I would probably make a scope for each format type and then use Ruby to determine which to use. Or create a method that determines the sort order and passes that to wherever you are using it.