Reputation: 6011
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.
Upvotes: 4
Views: 2559
Reputation: 7480
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
Upvotes: 13
Reputation: 5206
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!
Upvotes: 0