2

我对在控制器中管理实例变量感到不知所措,所以我在想是否有更好的方法来管理它们。

我的情况是,我有一个PagesController处理首页渲染。在首页,我有多个最初属于不同控制器的小表单(例如,创建一个新的帖子表单,并且有一个专用于它的 PostsController 但为方便起见,您可以在首页轻松发布。)和他们都需要相应的实例变量来保存表单(例如,新的帖子表单需要一个@post 对象)。

对我来说,我必须手动将这些实例变量添加到我PagesController#index的表单中才能使表单工作,所以很多行变得只是

@post = Post.new # similar for other objects
@some_other_var = OtherController.new # another one
@one_more = AnotherController.new # again
# even more @variables here when the website is big

如果这看起来还不够糟糕,请考虑何时createedit操作失败(例如未通过验证),我们需要渲染前一页。我们需要再次添加这些行。实际上,只要有渲染,我们就需要包含所有这些变量。

为每个需要它们的操作手动键入此类代码似乎非常麻烦,而且当网站变得复杂时,很容易错过其中的一两个。

所以我想知道是否有更好的方法来管理这些变量,这样我们只需要包含它们一次,而不是每次都编写相同的代码。

4

2 回答 2

2

你可以创建一个类似的before_filter东西:

class ApplicationController < ActionController::Base
  ...
  ...
  protected

    def instance_variables_for_form
      @post = Post.new # similar for other objects
      @some_other_var = OtherController.new # another one
      @one_more = AnotherController.new # again
      # even more @variables here when the website is big
    end

  end

并像这样使用它:

  class PagesController < ApplicationController
    before_filter :instance_variables_for_form, only: [:action]
    ...
    ...
  end

然后您也可以在需要时从任何操作中显式调用它。

于 2013-10-20T04:03:05.813 回答
0

如果这些变量可以在逻辑上分组,您应该考虑将它们放入 Presenter 对象中。

这是一篇很好的博客文章,解释了这个想法:http ://blog.jayfields.com/2007/03/rails-presenter-pattern.html

于 2013-10-20T08:18:09.727 回答