首页 > 解决方案 > 使用 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因为它也来自连接表。

标签: sqlruby-on-railsactiverecordruby-on-rails-5

解决方案


您的解决方案没有任何风险。即使您为 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)

推荐阅读