sql - 使用 ActiveRecord 语法从 Rails 中的连接表中选择或按列排序
问题描述
这是我想要做的:
Aquarium
.select(:id, :name, :yr_built, 'fishes.name')
.joins(:fishes)
.where(fishes: {name: "Nemo"})
.order('fishes.bday DESC')
这目前按预期工作,因为我输入了原始 SQL 代码。但是,因为有人告诉我使用原始 SQL 是一种不好的做法,并且会让您容易受到漏洞的影响,所以我想使用正确的 ActiveRecord 语法重构选择和排序行。
我知道在 a中,您可以使用语法.where
从连接表中查找值。table_name: {column_name: "value"}
而且我知道,如果我想按 aquariums 表中的列排序,我可以这样做:.order(col_name: :desc)
因为 aquariums 是开头的表。.order
但是当我尝试像这样添加它时,这似乎不起作用:.order(fishes: {bday: :desc})
我也不确定如何从原始 SQL 转换'fishes.name'
,.select
因为它也来自连接表。
解决方案
您的解决方案没有任何风险。即使您为 ActiveRecord 使用一些字符串参数 - 也无处可将 SQL 注入放在那里。只需更改'fishes.name'
为'fishes.name AS fish_name'
在结果中保留两个名称。
但是,如果您更喜欢无 SQL 字符串的解决方案(就像我一样),您可以使用 Arel 来白化这样的东西。
Aquarium
.joins(:fishes)
.select(:id, :name, :yr_built, Fish.arel_table[:name].as('fish_name'))
.where(fishes: { name: 'Nemo'})
.order(Fish.arel_table[:updated_at].desc)
推荐阅读
- c# - Automapper ValueConverter 的单元测试用例,模拟映射器未返回预期模型
- keycloak - 如何将来自身份提供者的声明映射到 Keycloak 中的角色组?
- elasticsearch - 弹性响应修改器插件
- c - C 混淆中的文件处理(从文件中读取矩阵)
- dart - dart typedef 子类函数失败
- python - 'OSError: [Errno 98] Address already in use' 在 kubernetes 上部署
- android - 如何将 ImageView 设置到 ConstraintLayout 的右侧
- c# - 使用服务帐户将 MS Word docx 文件加载到 Google Drive 时出现问题
- json - 使用 CookiePro 的 Adsense 5.1 错误和带外信号
- c# - 如何创建具有一定数量插槽的线程池并等待它们继续?