3

I am a relative newbie so would really appreciate any assistance.

I'm using Rails 4.2, with the Clearance gem for authentication. I'm hoping someone could describe the best practise for over-riding the controllers to include custom attributes on the sign_up form.

I've read a lot of suggestions with varied advice, many of which are from previous versions of rails that do not use strong_parameters.

If anyone could provide a brief breakdown of the methods I need to be over-riding (user_params/user_from_params/etc) I would be most grateful. I can get things functioning by defining a new 'new' method that just includes @user = User.new, and the a new 'user_params' method using .permit, but I'm concerned about the default code I'm bypassing in user_from_params.

Any advice on best practise here would be fantastic!

Thanks

2 Answers2

6

First, extend Clearance::UsersController and override #user_params to permit the new attribute(s):

# app/controllers/users_controller.rb
class UsersController < Clearance::UsersController

  private

  def user_params
    params[:user].permit(:email, :password, :your_custom_attribute)
  end
end

Then, update your routes file to use your new controller:

# config/routes.rb
resources :users, controller: :users, only: :create
psparrow
  • 9,808
  • 1
  • 17
  • 11
  • 1
    Thanks! This works just as you'd expect. The only thing I'd add is making `user_params` a `private` method. – DavidVII Feb 08 '16 at 05:57
  • @psparrow doesn't this cause issues in your `new` action? Pretty sure you will need to also override either `new` or `user_from_params`... – Hugh Middleton May 15 '16 at 23:23
  • You need to route to `#new` as well, otherwise you will get an **ActiveModel::UnknownAttributeError** . The line should be: `resources :users, controller: :users, only: [:new, :create]` – user3574603 Nov 08 '21 at 19:04
0

I'm working when I have time on updating the docs for Clearance, but right now the simplest thing to do is to inspect the Clearance users controller to see the various methods that can be overridden.

The default implementation of user_from_params is a bit odd now because Clearance 1.x still supports Rails 3.x, so it was written for a time when we used attr_accessible rather than strong parameters.

I'd probably do something like:

def user_params
  # Use strong params to do what you need
end

def user_from_params
  User.new(user_params)
end

You may need to massage user_params a bit so that whatever you do there is still valid for the new action, as user_from_params is still used there. I've opened an issue in Clearance to see if we can improve that aspect before 2.0.

Derek Prior
  • 3,497
  • 1
  • 25
  • 30