如何解决Ruby:将 Arel.sql 转换为 Arel::Nodes::Case 的想法?
我正在尝试重构一段代码(并提高我对 Arel::Nodes::Case
的理解)并且我想转换此 Arel.sql
语句
Arel.sql(default_order)
def default_order
"CASE
WHEN applications.status = 'new' AND owner_id IS NULL THEN '1'
WHEN applications.is_priority = '1' AND is_read = '0' AND owner_id = '#{current_user.id}' THEN '2'
WHEN applications.is_priority = '1' THEN '3'
ELSE '4'
END,applications.code"
end
进入 Arel::Nodes::Case
但我没有得到任何好的结果。有什么可以帮助的想法吗?
非常感谢。
更新
我采用了这种方法,但我根本不喜欢它。太难阅读和理解:
def default_order
arel_applications = Application.arel_table
Arel::Nodes::Case.new
.when((arel_applications[:status].eq('new'))
.and(arel_applications[:owner_id].eq(nil)),1)
.when((arel_applications[:is_priority].eq(1))
.and(arel_applications[:is_read].eq(0))
.and(arel_applications[:owner_id].eq(current_user.id)),2)
.when(arel_applications[:is_priority].eq(1),3)
.else(4).to_sql
end
即便如此,我也不知道如何获取在 sql 中用于对记录进行排序的 applications.code
。
解决方法
您不能总是期望 Arel
很漂亮。 Arel
是一个非常复杂且灵活的查询汇编程序,这种复杂性的副作用通常是冗长。
在我看来,使用 Arel
而不是原始 sql 总是优先考虑的,因为它是卫生的、动态的并且与数据库无关。
通过使用 then
方法而不是 when
的第二个参数,我们可以将您的更新更改为更具可读性。这将导致代码读起来更像 .when(condition).then(value)
之类的 CASE 语句。
更改看起来像这样:
def default_order
arel_applications = Application.arel_table
case_stmnt = Arel::Nodes::Case.new
.when(arel_applications[:status].eq('new').and(
arel_applications[:owner_id].eq(nil)
)
).then(1)
.when(arel_applications[:is_priority].eq(1).and(
arel_applications[:is_read].eq(0).and(
arel_applications[:owner_id].eq(current_user.id)
)
)
).then(2)
.when(arel_applications[:is_priority].eq(1)
).then(3)
.else(4)
end
现在来处理问题的第二部分“即便如此,我也不知道如何获取在 SQL 中用于对记录进行排序的应用程序代码。”>
我们可以使用 Arel::Nodes::Grouping
来处理:
def default_order
arel_applications = Application.arel_table
case_stmnt = Arel::Nodes::Case.new
.when(arel_applications[:status].eq('new').and(
arel_applications[:owner_id].eq(nil)
)
).then(1).
.when(arel_applications[:is_priority].eq(1).and(
arel_applications[:is_read].eq(0).and(
arel_applications[:owner_id].eq(current_user.id)
)
)
).then(2)
.when(arel_applications[:is_priority].eq(1)
).then(3)
.else(4)
Arel::Nodes::Grouping.new(case_stmnt,arel_applications[:code])
end
这将导致以下 SQL:
(CASE
WHEN [applications].[status] = N'new' AND [applications].[owner_id] IS NULL THEN 1
WHEN [applications].[is_priority] = 1 AND [applications].[is_read] = 0 AND [applications].[owner_id] = 1 THEN 2
WHEN [applications].[is_priority] = 1 THEN 3
ELSE 4 END,[applications].[code])
然后您可以将其用作 order
的参数(无需转换 to_sql
,因为 Rails 会为您处理此问题,例如 Application.order(default_order)
您还可以将排序方向附加到 case_stmnt
和 arel_applications[:code]
列,例如case_stmnt.asc
或 case_stmnt.desc
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。