1

I have a Ruby/Padrino project using Sequel ORM to access a legacy database in MySQL. The problem I am having is that several of the tables have a user editable column that is also a Primary Key.

I am trying to set up Sequel to catch any duplication errors within the application itself before MySQL can throw an error. I assumed that the validation helpers in Sequel could help me do that, but it appears they do not kick in before the data is saved.

My SQL table is defined as:

CREATE TABLE `dblocations` (
  `code` varchar(3) NOT NULL,
  `description` varchar(100) NOT NULL,
  PRIMARY KEY (`code`)
)

and my Sequel models are defined as follows:

class Location < Sequel::Model(:dblocations)
  plugins :validation_helpers
  def validate
    super
    validates_presence [:code, :description]
    validates_unique :code
  end
end

the problem is now, when I try the following code to insert Location Code 'ABC' into the database (when there is already another row in there with the Code 'ABC'), Ruby throws the following error:

Location.insert(:code => "ABC", :description => "Test Location")

ERROR -  Mysql2::Error: Duplicate entry 'ABC' for key 'PRIMARY': INSERT INTO `dblocations` (`code`, `description`) VALUES ('ABC', 'Test Location')
Sequel::UniqueConstraintViolation: Mysql2::Error: Duplicate entry 'ABC' for key 'PRIMARY'

Have I misconfigured my validations or is there another plugin I need to invoke?

CyberFerret
  • 275
  • 3
  • 8

1 Answers1

1

insert is a dataset-level method, validations are model level. You probably want to use create instead of insert.

Jeremy Evans
  • 11,959
  • 27
  • 26
  • Thank you - I didn't recognise the different levels between datasets and model. `Location.create(...)` works great. Pro Tip: I had to do `Location.unrestrict_primary_key` first as well, seeing as `:code` is a PK that I am manually changing. – CyberFerret May 23 '16 at 23:13