【问题标题】:Package instance variables in rails controllers?在 Rails 控制器中打包实例变量?
【发布时间】:2013-10-20 03:26:07
【问题描述】:

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

我的情况是,我有一个处理首页渲染的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

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

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

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

【问题讨论】:

    标签: ruby-on-rails ruby web


    【解决方案1】:

    你可以创建一个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
    

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-06
        • 2014-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多