ruby-on-rails 尝试使用rolify gem创建角色时出错

91zkwejq  于 2022-11-26  发布在  Ruby
关注(0)|答案(1)|浏览(135)

如何使用rolify gem?我还不能在控制台上运行它来试用它。我按照文档进行了操作。从文件跟踪中得到了这个错误-ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR: null value in column "item_id" violates not-null constraint)DETAIL: Failing row contains (919, Role, null, create, null, null, 2022-11-25 11:24:25.649806, null, {"id": [null, 1], "name": [null, "admin"], "created_at": [null, ...)..我搜索了它,发现一些列可能需要UUID,但得到了一个ID。我的角色表如下所示-

# frozen_string_literal: true

class RolifyCreateRoles < ActiveRecord::Migration[6.1]
  def change
    create_table(:roles) do |t|
      t.string :name
      t.references :resource, type: :uuid, polymorphic: true

      t.timestamps
    end

    create_table(:users_roles, id: false) do |t|
      t.references :user, type: :uuid
      t.references :role
    end

    add_index(:roles, [:name, :resource_type, :resource_id])
    add_index(:users_roles, [:user_id, :role_id])
  end
end

我已经花了很多时间试图调试它,但无济于事。
我可以做User.first.rolesUser.first.has_role?(:admin),但做User.first.add_role(:admin)给我上面的错误,从文件线索宝石。
我还尝试将角色表的ID设置为UUID,但它抛出了此错误-ActiveRecord::StatementInvalid (PG::UndefinedFunction: ERROR: operator does not exist: uuid = bigint) LINE 1: ... "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_r... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
我的书面记录表看起来像这样-

def change
    create_table :versions do |t|
      t.string   :item_type, null: false
      t.uuid     :item_id,   null: false
      t.string   :event,     null: false
      t.string   :whodunnit
      t.text     :object, limit: TEXT_BYTES
      t.datetime :created_at
    end
    add_index :versions, %i[item_type item_id]
  end

我无法将item_id类型更改为integer,因为整个应用程序都在使用它。
我使用的是rails 6.1和ruby 2.7。

waxmsbnn

waxmsbnn1#

如果要使用uuid而不是bigint作为主键,还需要设置对该表的任何引用的类型:

class RolifyCreateRoles < ActiveRecord::Migration[6.1]
  def change
    create_table(:roles, id: :uuid) do |t|
      t.string :name
      t.references :resource, type: :uuid, polymorphic: true
      t.timestamps
    end

    create_table(:users_roles, id: false) do |t|
      t.references :user, type: :uuid
      t.references :role, type: :uuid # this was missing
    end

    add_index(:roles, [:name, :resource_type, :resource_id])
    add_index(:users_roles, [:user_id, :role_id])
  end
end

相关问题