Search code examples
ruby-on-railsruby-on-rails-3devise

Rails Devise add role based on signup path


I'm building a Rails 3 app, where I need to give users specific roles based on the path they take to sign up on the site. I am using Devise and Cancan.

So for instance, the path

new-fundraiser (or /users/new/fundraiser)

Needs to set user.fundraiser = true on user creation, and

new-charity-user (or /users/new/charity)

Needs to set user.charity_owner = true on user creation.

What is the easiest / best-practice way to accomplish this using Devise and Cancan?


Solution

  • I would set up a route like:

    match "/users/new/:role", :to => 'users#new'
    

    In your user model I'd add an accessor:

    class User < ActiveRecord::Base
      def role=(role_name)
        @role = role_name
        case role_name
        when 'charity'
          self.charity_owner = true
        when 'fundraiser'
          self.fundraiser = true
        else
          # raise some exception
        end
      end
    
      def role
        @role
      end
    end
    

    Then in your users#new.html.erb form add a hidden field:

    <%= form.hidden_field :role, :value => params[:role] %>
    

    Then your won't need to change your controller code at all.