MartinJNash / Royce

A Ruby on Rails roles solution.
MIT License
210 stars 14 forks source link

Named Scopes and Return All Instances of Role not working with subclasses #9

Open jeff-savin opened 9 years ago

jeff-savin commented 9 years ago

If I have a subclass of User, say Admin, with royce_roles [:add, :edit, :delete, :crud], the following gives me empty collections:

@admin = Admin.first
@admin.add_role :crud
Admin.cruds  # returns empty

crud_role = Royce::Role.find_by(name: 'crud')
crud_role.admins.all  # returns empty

Looking in SQL, royce_connector shows User as roleable_type instead of Admin which is what is causing the empty sets.

jeff-savin commented 9 years ago

To expand a little on the above, I noticed doing a user.role_list builds this SQL query:

SELECT `royce_role`.`name` FROM `royce_role` INNER JOIN `royce_connector` ON `royce_role`.`id` = `royce_connector`.`role_id` WHERE `royce_connector`.`roleable_id` = 641702 AND `royce_connector`.`roleable_type` = 'User'

and the crud_role.admins.all builds this SQL query

SELECT `users`.* FROM `users` INNER JOIN `royce_connector` ON `users`.`id` = `royce_connector`.`roleable_id` WHERE `users`.`type` IN ('Admin') AND `royce_connector`.`role_id` = 1 AND `royce_connector`.`roleable_type` = 'Admin'

As mentioned in above note, the roleable_type here is stored as 'User' allowing the role_list to work, but not the named scopes as mentioned above.

jeff-savin commented 9 years ago

I've forked this and made changes, which seems to work. I'll submit a pull request if you're interested. Thanks.

grzlus commented 9 years ago

@jeff-savin It's always good to submit pull request.