Skip to content

How to grant badges on user using Devise

Tute Costa edited this page Aug 9, 2018 · 2 revisions

On Devise registration, without confirmation

1- Define the badge in config/initializers/merit.rb:

Merit::Badge.create!(
  id: 1,
  name: 'just-registered'
)

2- Add to app/models/merit/badge_rules.rb:

grant_on 'users/registrations#create', badge: 'just-registered', model_name: 'User'

3- Override Devise RegistrationsController. Add in the devise_for call in config/routes.rb:

devise_for :users, controllers: { registrations: 'users/registrations' }

4- Add a file app/controllers/users/registrations_controller.rb:

class Users::RegistrationsController < Devise::RegistrationsController
  def create
    @user = build_resource # Needed for Merit
    super
  end

  def update
    @user = resource # Needed for Merit
    super
  end
end

Done!

Note that this works if user is not required to confirm it's account before signing in (confirmable devise module). Related issue: https://github.com/tute/merit/issues/164.


After the confirmation action

1- Define the badge in config/initializers/merit.rb

2- Add to app/models/merit/badge_rules.rb:

# Note: long line! Be sure to scroll
grant_on 'users/confirmations#show', badge: 'your-badge-name', model_name: 'User', to: :itself do
  User.count <= 100
end

3- Override Devise ConfirmationsController. Add in the devise_for call in config/routes.rb:

devise_for :users, controllers: { confirmations: 'users/confirmations' }

4- Add a file app/controllers/users/confirmations_controller.rb:

class Users::ConfirmationsController < Devise::ConfirmationsController
  def show
    super
    @confirmation = resource # Needed for Merit / Must be AFTER the super
  end
end

Done ! :)