我有一个模型 User 和一个相应的 UsersController。由于项目发生变化,CentersController 中需要为用户模型提供相同的、精确的功能,当然,仅具有针对中心的附加功能。 UsersController 保持原样。
设计问题是如何使用 UsersController 方法(更新、编辑、创建等)而不在 CentersController 中复制它们?例如,当用户在中心 View 中更新时,将调用用户 Controller 的更新操作,但查看器应重定向回中心 View 。
最佳答案
这就是模块或“mixin”的用途。您将常用方法放入一个模块中,并将该模块包含到 UsersController
和 CentersController
中。
module Foo
def bar
end
end
class UsersController < ApplicationController
include Foo
end
class CentersController < ApplicationController
include Foo
end
或者,将通用代码放入 Controller 中,并从该 Controller 继承:
class FooController < ApplicationController
def bar
end
end
class UsersController < FooController
end
class CentersController < FooController
end
关于ruby-on-rails - rails : two controllers for the same model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12163768/