Maksim Kachalin Maksim Kachalin - 2 months ago 12
Ruby Question

'Sequel::Error: id is a restricted primary key' when creating record using Sequel

I have a model based on Sequel and Oracle adapter:

class Operation < Sequel::Model(DB[:operations])
end


If I try to create a record using Oracle's sequence.nextval as primary key:

Operation.create(
:id=>:nextval.qualify(:Soperations),
:payee_id=>12345,
:type=>"operation",
:origin=>"user-12345",
:parameters=>{}.to_s
)


I've got error:
Sequel::Error: id is a restricted primary key
.
What's the correct way to create a record in such case or "map" Oracle's sequence to
id
column? Or maybe, I have to use
unrestrict_primary_key
?

Answer

unrestrict_primary_key will allow you to mass assigned to the primary key field. However, that probably isn't what you want to do in this case, unless you also wanted to turn off typecasting. Since you just want to set a value on creation, I recommend using before_create:

class Operation
  def before_create
    values[:id] ||= :nextval.qualify(:Soperations)
    super
  end
end 
Comments