Rails Add rolify role via user form

cancan, devise, ruby, ruby-on-rails-3

Solution

At the end I preferred to drop off Rolify. It was taking too much time for me, and I realized I need a much simpler solution so I'm now using a new column in my model describin the user, and I've also implemented a method similiar to has_role? to keep compatibility with CanCan.

This has solved a lot of problems, and it's a more common solution (= easier help).

In my experience I noticed that if nobody answer your question on SO whithin 30 minutes, then you're doing it too complex.

Thanks everybody.

Problem

I'm creating an application based on Devise, CanCan and Rolify to handle private resources. Devise registration has been disabled since I don't want allow users to registrer, while I'm creating an admin interface to add/edit users. Now I'm dealing with user role. I'd like to allow admin to create users and set their role using the same form. I don't know what kind of relation is using rolify because I'm pretty new to rails and Ruby and rolify added the `rolify` method instead of a more clear relation. I currently need and want to only have one role per user. So if someone edits the user changing the role I delete all `@user.roles` and then set the new one. I'm currently having it to work using a simple hack. I've added a select field to the form, using a collection of `Role`s to provide a selection of roles. Then inside the `create` and `update` methods I'm doing this: ``` role = params[:user][:role] params[:user].delete :role @user = User.new(params[:user]) respond_to do |format| if @user.save # update_attributes inside update @user.add_role role # ... end end ``` As you may see I'm not interacting with the `Role` model directly but using the provided `add_role` method. This also creates another issue, because I have to retrieve the current role to allow the update view to set the proper default value for the select (beside the most important fact that I don't know how to validate the presence of ONE role). This is going to be a too dirt solution, so I'd like to have some point of view, and maybe some suggestion on how to do this. I've spent all the day working on this :-( If you need some info please ask me. P.S. I'm watching a screenscast about nested resources but in the DB I may see that it's using a third table to keep track of `users_roles` and I'm not understanding how to do it. Thanks!!

Original source