I struggle with modeling my table to Rails model with custom primary key and id as a regular (not null) column.
The problem is my table has:
auto_idprimary key column with AUTO_INCREMENTidas custom column withNOT NULLconstraint on it (it should be set by the application side before saving)
class InitialMigration < ActiveRecord::Migration[6.1]
def change
create_table :cars, id: false, force: true do |t|
t.primary_key :auto_id
t.string :id, null: false
end
end
end
I want to:
- Make the
primary_keybeing auto generated by database. - Set the
idvalue directly in the application before saving the model.
But when I try to save a Car instance to database I have a problem with setting id from the app.
class Car < ActiveRecord::Base
self.primary_key = "auto_id"
before_create do
binding.pry
end
end
Even in the binding.pry line, when I call self.id = '1234' it's being reassigned to auto_id field, instead of id.
Thus id columns always remain NULL which leads to a DB error Field 'id' doesn't have a default value.
[2] pry(#<Car>)> self.id = '9'
=> "9"
[3] pry(#<Car>)> self
=> #<Car:0x00007fcdb34ebe60
auto_id: 9,
id: nil>
PS. It's Rails 6.