Search code examples
rubysequel

Save (possibly) duplicate Sequel Model instance


In Sequel, if you have a Model class called MyModel, you can do something like this:

#make MyModel instance
row = MyModel.new(column1, column2)
#save it to the database Sequel is connected to
row.save

However, "row.save" will fail if you're saving a duplicate primary key.

I'm looking for a method that will save a value to the database if the primary key is not duplicate and save nothing, without failing, otherwise.

I have looked through the instance methods for Sequel Model, but I haven't found what I'm looking for. Is there a way I can do this?


Solution

  • I've not used Sequel before, but you could always wrap the call to save with a begin/rescue block and just swallow the error without doing anything (you almost always want to do SOMETHING).

    begin
      row = MyModel.new(col1, col2)
      row.save
    rescue Sequel::DatabaseError => e
      # handle error here
    end
    

    Note: you might want something other than DatabaseError above.