6

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?

Maksim Kachalin
  • 132
  • 1
  • 8

2 Answers2

7

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 
Jeremy Evans
  • 11,361
  • 23
  • 25
3

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

Operation.new(attrs).tap { |o| o.id = id }
cema-sp
  • 352
  • 2
  • 7