Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Is it possible to achieve something like this?

  • Suppose name and plural_name are fields of Animal’s table.
  • Suppose pluralise_animal is a helper function which takes a string and returns its plural literal.
  • I cannot loop over the animal records for technical reasons.
  • This is just an example
Animal.update_all("plural_name = ?", pluralise_animal("I WANT THE ANIMAL NAME HERE, the `name` column's value"))

I want something similar to how you can use functions in MySQL while modifying column values. Is this out-of-scope or possible?

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.

Thanks in advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I cannot loop over the animal records for technical reasons.

Sorry, this cannot be done with this restriction.

If your pluralizing helper function is implemented in the client, then you have to fetch data values back to the client, pluralize them, and then post them back to the database.

If you want the UPDATE to run against a set of rows without fetching data values back to the client, then you must implement the pluralization logic in an SQL expression, or a stored function or something.

UPDATE statements run in the database engine. They cannot call functions in the client.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading