Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: how should I share logic between controllers?

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.

like image 681
djb Avatar asked Dec 12 '22 10:12

djb


1 Answers

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
like image 63
axsuul Avatar answered Dec 31 '22 17:12

axsuul