4

This question must have been asked already, but I can't find it.

I have a UsersController and an Admin::UsersController. Obviously a lot of what goes on in these classes (eg the implementation of strong_parameters, the paths to follow after creating/editing a user) are the same.

Can I - indeed, ought I? - share code between these controllers? Is this what concerns are for? The examples I find for them online tend to deal with models.

Any guidance much appreciated.

2
  • 1
    are they really going to be the same? Can admins edit the same list of fields as a general user? Will they redirect to the same place? Seems logical that a user would redirect to their profile after editing themselves, and an admin would redirect to a user list. Commented Oct 8, 2013 at 1:13
  • @sevenseacat, in the long term, probably not. but it's useful to share the strong_params for now, now that there's no more attr_accessible at the model level, if i understand correctly Commented Oct 8, 2013 at 10:08

2 Answers 2

13

Use concerns (put in app/controllers/concerns)

module UsersControllable
  extend ActiveSupport::Concern

  def new
  end

  def create
  end

  private
  def user_params
    # strong params implementation
  end
end

class UsersController < ApplicationController
  include UsersControllable
end

class Admin::UsersController < ApplicationController
  include UsersControllable
end
Sign up to request clarification or add additional context in comments.

Comments

0

One way is using inheritance. Create a new controller:

class SharedUserController < ApplicationController
  # With shared code
end

And then:

class UsersController < SharedUserController
end

class Admin::UsersController < SharedUserController
end

Hope this help!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.