I have two separate controllers that inherit from Admin::UserBaseController, display a searchable, sortable table of users, and use the same partial views.
Admin::UsersController– Display users within the context of a given organization.Admin::OrganizationsController– Displays all users for the system.
Here is the index method of Admin::UsersController:
def index
q = "%#{params[:search]}%"
@users = User.where("first_name like ? or last_name like ? or username like ?", q, q, q).order(sort_column + ' ' + sort_direction).paginate(:page => params[:page])
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @users }
end
end
Here is the edit method of Admin::OrganizationsController:
def edit
@organization = Organization.find(params[:id])
q = "%#{params[:search]}%"
@users = @organization.users.where("first_name like ? or last_name like ? or username like ?", q, q, q).order(sort_column + ' ' + sort_direction).paginate(:page => params[:page])
end
There is a lot of similarity between the two methods in the way that the @users variable is assigned. It’s a difference of User and @organization.users and that’s it. How do I DRY this up?
So what this screams is scopes. This removes the duplicate queries into a single place in the model and enables you to chain scopes onto the class and associations.
Then in Admin::UsersController
In Admin::OrganizationsController:
Making everything nice and succinct.