Rails - 如何在更新语句中引用模型自身的列值?

Rails - How to reference model's own column value during update statement?

有没有可能达到这样的效果?

Animal.update_all("plural_name = ?", pluralise_animal("I WANT THE ANIMAL NAME HERE, the `name` column's value"))

我想要类似于在 MySQL 中修改列值时如何使用函数的方法。这是超出范围还是可能?

UPDATE animals SET plural_name = CONCAT(name, 's') -- just an example to explain what I mean by referencing a column. I'm aware of the problems in this example.

提前致谢

I cannot loop over the animal records for technical reasons.

抱歉,此限制无法完成。

如果您的复数化辅助函数是在客户端实现的,那么您必须将数据值取回客户端,将它们复数化,然后 post 将它们传回数据库。

如果您希望对一组行进行 运行 更新而不将数据值取回客户端,那么您必须在 SQL 表达式或存储函数中实现复数逻辑什么的。

数据库引擎中的更新语句运行。他们不能调用客户端中的函数。

使用 ruby 脚本生成 SQL 脚本,将复数值插入到临时 table

File.open(filename, 'w') do |file|
  file.puts "CREATE TEMPORARY TABLE pluralised_animals(id INT, plural varchar(50));"
  file.puts "INSERT INTO pluralised_animals(id, plural) VALUES"
  Animal.each.do |animal|
    file.puts( "( #{animal.id}, #{pluralise_animal(animal.name)}),"
  end
end

注意:用分号(;)替换结尾的逗号(,)

然后 运行 在数据库中生成 SQL 脚本来填充临时文件 table。

最后 运行 数据库中的 SQL 更新语句将临时 table 连接到主 table...

UPDATE animals a
INNER JOIN pluralised_animals pa 
  ON a.id = pa.id
SET a.plural_name = pa.plural;