0

I have a permissions model that is based on an individual Store. A store has a member that can view data has_and_belongs_to_many_users, edit data has_and_belongs_to_many_editors and own the Store has_and_belongs_to_many_owners.

If I were to add more permissions in the future, I would have to add more joins. I'm not sure I like this model.

Store has_and_belongs_to_many_users
Store has_and_belongs_to_many_owners -> [Users]
Store has_and_belongs_to_many_editors -> [Users]

An alternative is this, I factor out the role, and create a second join table called "authorized users".

Here is what that could look like:

Store has_and_belongs_to_many_authorized_users
authorized_users: User_id Role_id

How can I use a second join table, that is called "authorized_users" with rails? Looking at my model, I do not have a model called authorized_users, and I am not sure how to build a model that relates to a join table.

essentially my question is, with Rails, How can I join a join table with a join table?

JZ.
  • 21,147
  • 32
  • 115
  • 192

2 Answers2

1

Just answering your question as it is stated, I would prefer to put the roles in the join table myself

class User < ActiveRecord::Base
  has_many :store_users, inverse_of: :user, dependent: :destroy
  has_many :stores, through: :store_users
end

class Store < ActiveRecord::Base
  has_many :store_users, inverse_of: :store, dependent: :destroy
  has_many :users, through: :store_users
end

class StoreUser < ActiveRecord::Base
  belongs_to :store
  belongs_to :user
  has_many :permissions, dependent: :destroy, inverse_of: :store_user

  validates_presence_of :store, :user
end

class Permission < ActiveRecord::Base
  belongs_to :store_user
  validates_presence_of :role
end
ilan berci
  • 3,883
  • 1
  • 16
  • 21
0

If you need a join table, that can or should be a model, you want to use has_many :trough association. You can read more about it here: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Danny Ocean
  • 1,081
  • 2
  • 14
  • 30