How to update existing record if the one being saved has the same key?

Posted by Pavel Shved on Stack Overflow See other posts from Stack Overflow or by Pavel Shved
Published on 2010-05-12T09:59:02Z Indexed on 2010/05/12 12:34 UTC
Read the original article Hit count: 187

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about activerecord

Related posts about ruby