Using ready-made Devise and CanCan, I set up my user "roles" in accordance with the Rails Casts # 189 "Embedded Association". However, I was not able to get @cailinanne's answer to work with my setup, as Roles was supposed to have a different approach. If anyone has a similar issue, here is a much less elegant / robust approach, which is borrowed from @cailinanne's answer. It has one advantage: no need to modify the User model.
Use the devise_scope route and the link_to code provided by @cailinanne. Skip the changes to the user model. Finally, use the following code in views / development / registration / new.html.erb:
<% if params[:initial_role] == "admin" %> <%= hidden_field_tag "user[roles][]", :admin %> <% elsif params[:initial_role] == "moderator" %> <%= hidden_field_tag "user[roles][]", :moderator %> <% elsif params[:initial_role] == "author" %> <%= hidden_field_tag "user[roles][]", :author %> <% end %>
This code replaces the check_box_tag code provided in the Rails Cast code.
It definitely needs extra work. I will translate the if-elsif-elsif logic into the controller at some point and reference it to User.ROLES so that it does not break if I add / remove a role. But this will help you get the initial role assignment if you adopted the Rails Cast role approach.
source share