Arman H
Arman H

Reputation: 5618

Proper use of Sequel's save()? How to create new or update existing records?

The Sequel gem has a save method that "creates or updates the record". I'm trying to use it for creating a new record, when one doesn't exist, or updating fields for existing records:

record = Records.where(:name => 'Dark Side of the Moon').first
record.save(:artist => "Pink Floyd")

This fails, because Records.where(:name => 'Dark Side of the Moon') returns nil, not an empty Record object. Essentially, I'm using this method as an upsert, and it doesn't work this way, since the save method is a model instance method.

My question is twofold: (1) what's the correct way of using save, and (2) does Sequel have a way of "upserting" records?

Upvotes: 2

Views: 2596

Answers (2)

Lane
Lane

Reputation: 5006

record.save(:artist => "Pink Floyd") did not work for me, but

record.artist = "Pink Floyd"
record.save

worked well. It might be a bug in Sequel 4.16.0.

Upvotes: 1

Jeremy Evans
Jeremy Evans

Reputation: 12139

You can only use Model#save if you have a model instance. You can do that by creating a new model instance if there isn't one already in the database (when nil is returned).

record = Records[:name => 'Dark Side of the Moon'] || Records.new(:name => 'Dark Side of the Moon')
record.save(:artist => "Pink Floyd")

Upvotes: 3

Related Questions