Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'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?

like image 281
Maxim Kachalin Avatar asked Feb 15 '12 11:02

Maxim Kachalin


2 Answers

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 
like image 77
Jeremy Evans Avatar answered Sep 28 '22 00:09

Jeremy Evans


To simply create a new instance with needed id you can:

Operation.new(attrs).tap { |o| o.id = id }
like image 29
cema-sp Avatar answered Sep 27 '22 22:09

cema-sp