DEV Community

Jeremy Woertink
Jeremy Woertink

Posted on

Using custom IDs in Lucky

If you're using Lucky, and you have a schema that's not default, you may need to create a custom primary key.

I had to do this for an app where my primary keys were defined in postgres like character varying(18). Just doing String wasn't going to be good enough since Avram defines those as just text. Here's how I did it.

# src/models/concerns/custom_id.cr
alias CustomID = String

module Avram::Migrator::Columns::PrimaryKeys
  class CustomIDPrimaryKey < Avram::Migrator::Columns::PrimaryKeys::Base
    def initialize(@name)
    end

    def column_type : String
      "character varying(18)"
    end
  end
end

module Avram::Migrator::Columns
  class CustomIDColumn < Avram::Migrator::Columns::Base
    @default : String? = nil

    def initialize(@name, @nilable, @default)
    end

    def column_type
      "character varying(18)"
    end
  end
end

Enter fullscreen mode Exit fullscreen mode

Then in my model, I can now do this:

# src/models/user.cr
class User < BaseModel
  skip_default_columns
  table do
    primary_key id : CustomID
    column created_on : Time
    column updated_on : Time
  end
end
Enter fullscreen mode Exit fullscreen mode

Discussion (0)