Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails active record: update a table with join

I'm working on a rails project. I have two tables storing data from disparate systems: tasks and projects.

With a condition, Projects knows Tasks through ref_id, but not in the opposite direction. so, once matches found from a join, I'd like to set task.project_id with the matched Projects table's id.

UPDATE FROM task AS t
LEFT JOIN projects as p
ON t.ref_id = p.ref_id
SET t.project_id = p.id

my question here is: how can I achieve this using active record in rails?

like image 996
Sarun Sermsuwan Avatar asked Mar 20 '12 09:03

Sarun Sermsuwan


1 Answers

If you're using postgres you can run an update_all with a "join" from the model like:

Task.connection.update_sql("UPDATE tasks AS t SET project_id = p.id FROM projects AS p WHERE t.ref_id = p.ref_id")

Note: the update_sql call is deprecated for Rails 5 and should be switched to just update

Since you are sending sql directly you need to make sure you are using syntax appropriate for your database.

like image 86
vansan Avatar answered Oct 13 '22 00:10

vansan