如何在ActiveRecord的关系表中使用枚举?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在ActiveRecord的关系表中使用枚举?相关的知识,希望对你有一定的参考价值。

我具有静态权限,我不需要存储在数据库中并创建具有权限的更多表,我想使用Enum:

enum permission: [:show, :create, :update, :destroy]

模型中需要做些什么,以便我可以将Enum用作角色:

Role.first.permission
=>"create"

我有移民:

class CreateRoles < ActiveRecord::Migration
  def change
    create_table :roles do |t|
        t.string :name
    end
  end
end

class CreateCompanies < ActiveRecord::Migration
  def change
    create_table :companies do |t|
      t.string :name
    end
  end
end

class CreateCompaniesRoles < ActiveRecord::Migration
  def change
    create_table :companies_roles do |t|
      t.integer :company_id
      t.integer :role_id
      t.integer :permission
    end
  end
end

schema in DB

角色和公司的关系has_many

答案

models/concerns目录中创建关注点,并在需要的所有模型中包括该关注点。

require 'active_support/concern'

module Permissible 
  extend ActiveSupport::Concern

  included do
    enum permission: [:show, :create, :update, :destroy]
  end
end

在您的CompaniesRole模型中包括关注点

class CompaniesRole < ActiveRecord
  include Permissible
end

以上是关于如何在ActiveRecord的关系表中使用枚举?的主要内容,如果未能解决你的问题,请参考以下文章