Rails consistency for a method in multiple controllers

I have an application that has users whose profiles are accessible through site.com/username. Choosing a username, I make an AJAX call to a method in my UserController to make sure the username is available (and also check, like at the end, when it is sent). Now I want to add groups that will also be available through site.com/groupname. Since group and user names cannot collide, any controller method that answers an AJAX call will have to check both options, so the check_username_available and check_groupname_available methods will do the same. What is the best practice / Rails way to handle this since I don't want to replicate the code in both UserController and GroupController?

Having a method for each controller seems a little redundant, even if the functionality is displayed to the assistant, since there will still be two routes that do the same. Having a separate controller also solves the problem, but I'm not sure if this is a good Rails practice.

+4
source share
2 answers

which can be reused through the module

class UsersController < ActionController::Base include NameUniqueness end class GroupsController < ActionController::Base include NameUniqueness end module NameUniqueness protected def check_name # implementation here end end 

both controllers will now have access to the instance of the check_name instance.

+4
source

DanPickett's answer is great.

Another option is to create a class method in the user model and simply call it from each controller. Since this name check seems to work for the model, I would do it.

 class User def self.check(stuff) ... 
0
source

Source: https://habr.com/ru/post/1395109/


All Articles