1
votes

I've been reading up on a bit of STI Inheritence examples for Rails, While it looks like it would suit my needs (User role/types inheriting from a base class of user). It seems like it doesn't handle a user having multiple roles too well. Particularly because it relies on a type field in the database.

Is there a quick and easy work around to this?

3

3 Answers

3
votes

I'm not sure if STI is the right solution in a user role/user scenario - I don't think of User roles/types as a specific form of user. I would have the following schema:

class Membership < ActiveRecord::Base
  belongs_to :user     # foreign key - user_id
  belongs_to :role     # foreign key - role_id
end
class User < ActiveRecord::Base
  has_many :memberships
  has_many :roles, :through => :membership
end
class Role < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => :membership
end

Another way of doing this would be to use has_and_belongs_to_many. You might also want to check out the restful_authentication plugin.

1
votes

A good workaround for your problem could be the easy_roles gem. You can find it on github. As the others already said STI is not the way you can implement your stuff.

0
votes

Just like Andy said, has_and_belongs_to_many is another way to do this.

# user.rb
class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
end

# role.rb
class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
end

Note: You still need the association table in your database but it's just hidden from your models.