RailsDFW
RailsDFW

Reputation: 1573

Rails: two controllers for the same model

I have a model User and a corresponding UsersController. Due to project changes, the same, exact functionality for the User model needs to be in the CentersController, with additional functionality for Centers only of course. The UsersController stays as is.

The design question is how to use the UsersController methods (update, edit, create, etc) without replicating them in the CentersController? For example, when a user is updated in the view for Centers, the User controller's Update action will be called, but the viewer should be redirected back to Centers view.

Upvotes: 2

Views: 1210

Answers (1)

Mori
Mori

Reputation: 27779

This is what a module, or "mixin" is for. You put the common methods in a module, and include that module into both UsersController and CentersController.

module Foo
  def bar
  end
end

class UsersController < ApplicationController
  include Foo
end

class CentersController < ApplicationController
  include Foo
end

Alternatively, put your common code in a controller, and inherit from that controller:

class FooController < ApplicationController
  def bar
  end
end

class UsersController < FooController
end

class CentersController < FooController
end

Upvotes: 2

Related Questions