Skip to content

Change role join table association (HABTM) to a has_many through association #318

@phlegx

Description

@phlegx

Hi!

I want to add more data to the role join table. Actually rolify uses a HABTM table. Why don't change rolify to use a has_many through association? So, everybody can expand the role join table with custom data.

module Rolify
  ...
  def rolify(options = {})
    include Role
    ...

    rolify_options = { :class_name => options[:role_cname].camelize }
    # NOTE not needed any more
    # rolify_options.merge!({ :join_table => self.role_join_table_name }) if Rolify.orm == "active_record"
    rolify_options.merge!(options.reject{ |k,v| ![ :before_add, :after_add, :before_remove, :after_remove ].include? k.to_sym })

    # NOTE defining the association has_many through
    # has_and_belongs_to_many :roles, rolify_options
    has_many self.role_join_table_name.to_sym
    has_many :roles, rolify_options.merge!(through: self.role_join_table_name.to_sym)

   ...
  end

Here an example using a hstore (Postgresql) field:

    execute 'CREATE EXTENSION IF NOT EXISTS hstore'

    create_table :users_roles do |t|
      t.references :user, index: { with: :role_id }, null: false
      t.references :role, null: false
      t.hstore :configurations
      t.timestamps
    end

Here the model:

class UsersRole < ActiveRecord::Base

  store_accessor :configurations, :color

  validates :user, presence: true
  validates :role, presence: true
  validates :color,         ...

  belongs_to :user
  belongs_to :role

end

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions