Последовательность не начинается с начального номера, используя aparment gem

Я пытаюсь запустить последовательность с начальным номером в арендаторах, но только публичная схема получила это.

Посмотрите на мою миграцию:

class CreateDisputes < ActiveRecord::Migration[5.0]
  def change
    create_table :disputes, id: :uuid do |t|
      ...
      t.integer    :code
      ...
    end

    execute %{
      CREATE SEQUENCE disputes_code_seq INCREMENT BY 1
        NO MINVALUE NO MAXVALUE
        START WITH 1001 CACHE 1
        OWNED BY disputes.code;

      ALTER TABLE ONLY disputes
        ALTER COLUMN code SET DEFAULT nextval('disputes_code_seq'::regclass);
    }

    ...
  end
end

Спасибо!

1 ответ

Решение

Я не эксперт в apartement драгоценный камень. Но, apartment не создает disputes_code_seq в схеме арендатора.

Обходной путь для этого состоит в том, чтобы раскомментировать следующую строку в config/initializers/apartment.rb

  # Apartment can be forced to use raw SQL dumps instead of schema.rb for creating new schemas.
  # Use this when you are using some extra features in PostgreSQL that can't be respresented in
  # schema.rb, like materialized views etc. (only applies with use_schemas set to true).
  # (Note: this option doesn't use db/structure.sql, it creates SQL dump by executing pg_dump)
  #
  config.use_sql = true

С config.user_sql установлен в trueМиграция квартиры создаст последовательность для арендатора. Вот журнал (ы) из migration а также rails console для справки.

Ниже приведен журнал миграции

ubuntu@ubuntu-xenial:~/devel/apartment/testseq$ rails db:migrate
== 20170224161015 CreateDisputes: migrating ===================================
-- create_table(:disputes)
   -> 0.0035s
-- execute("\n      CREATE SEQUENCE disputes_code_seq INCREMENT BY 1\n      NO MINVALUE NO MAXVALUE\n      START WITH 1001 CACHE 1\n      OWNED BY disputes.code;\n\n      ALTER TABLE ONLY disputes\n        ALTER COLUMN code SET DEFAULT nextval('disputes_code_seq'::regclass);\n    ")
   -> 0.0012s
== 20170224161015 CreateDisputes: migrated (0.0065s) ==========================

        [WARNING] - The list of tenants to migrate appears to be empty. This could mean a few things:

          1. You may not have created any, in which case you can ignore this message
          2. You've run `apartment:migrate` directly without loading the Rails environment
            * `apartment:migrate` is now deprecated. Tenants will automatically be migrated with `db:migrate`

        Note that your tenants currently haven't been migrated. You'll need to run `db:migrate` to rectify this.

Ниже приведен журнал создания арендатора и добавления строки в disputes

irb(main):001:0> Apartment::Tenant.create('tenant2')
<output snipped for brevity>


irb(main):005:0> Apartment::Tenant.switch!('tenant2')
=> "\"tenant2\""
irb(main):006:0> d = Dispute.new
=> #<Dispute id: nil, code: nil, created_at: nil, updated_at: nil>
irb(main):007:0> d.save
   (0.2ms)  BEGIN
  SQL (0.6ms)  INSERT INTO "disputes" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id"  [["created_at", 2017-02-25 03:09:49 UTC], ["updated_at", 2017-02-25 03:09:49 UTC]]
   (0.6ms)  COMMIT
=> true
irb(main):008:0> d.reload
  Dispute Load (0.3ms)  SELECT  "disputes".* FROM "disputes" WHERE "disputes"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
=> #<Dispute id: 1, code: 1001, created_at: "2017-02-25 03:09:49", updated_at: "2017-02-25 03:09:49">

Как видно из следующего журнала, код начинается с порядковых номеров.

irb(main):009:0> d = Dispute.new
=> #<Dispute id: nil, code: nil, created_at: nil, updated_at: nil>
irb(main):010:0> d.save
   (0.3ms)  BEGIN
  SQL (0.6ms)  INSERT INTO "disputes" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id"  [["created_at", 2017-02-25 03:11:13 UTC], ["updated_at", 2017-02-25 03:11:13 UTC]]
   (0.5ms)  COMMIT
=> true
irb(main):011:0> d.reload
  Dispute Load (0.5ms)  SELECT  "disputes".* FROM "disputes" WHERE "disputes"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
=> #<Dispute id: 2, code: 1002, created_at: "2017-02-25 03:11:13", updated_at: "2017-02-25 03:11:13">
Другие вопросы по тегам