How to update existing record if the one being saved has the same key?
- by Pavel Shved
MySQL has a very nice option for INSERT statement, which is particularly helpful for join tables without the id column. It inserts a record, but, instead of throwing an error if its key clashed with the existing one, that record is updated. Here's an example:
INSERT INTO table (key1,key2,data) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=3;
How to achieve the same with ActiveRecord? The code looks like this:
class Model < ActiveRecord::Base
belongs_to :key1
belongs_to :key2
end
record = Model.new
record.key1 = key1
record.key2 = key2
record.data = 'new data'
record.WHAT? #Inserts or updates `data` for the existing record