【问题标题】:Rails 3 and Controller Instance Variables Inside a HelperRails 3 和 Helper 中的控制器实例变量
【发布时间】:2011-03-06 04:24:05
【问题描述】:

刚刚遇到类似http://www.ruby-forum.com/topic/216433的问题

我需要从助手访问控制器实例变量。

这是我完成的代码,但它不起作用。

控制器:

class ApplicationController < ActionController::Base
  helper_method :set_background_type #for action only background setting

  #for controller-wise background setting
  def set_background_type(string)
    @background_type = string
  end
end

助手:

module ApplicationHelper

  def background_type
    @background_type || 'default'
  end

end

布局:

<body class="<%= background_type %>">

【问题讨论】:

    标签: ruby-on-rails-3


    【解决方案1】:

    经过一番搜索。我从

    得到了一个解决方案

    http://api.rubyonrails.org/classes/ActionController/Helpers/ClassMethods.html

    控制器变成:

    class ApplicationController < ActionController::Base
      helper_method :set_background_type #for action only background setting
      helper_attr :background_type
      attr_accessor :background_type
    
      #for controller-wise background setting
      def set_background_type(string)
        @background_type = string
      end
    
      def background_type
        @background_type || 'default'
      end
    end
    

    并从 ApplicationHelper 中删除该方法。 它适用于这种情况,但我仍然很好奇,

    有没有办法访问 ApplicationHelper 中方法的控制器实例变量?

    【讨论】:

      【解决方案2】:

      如果你正在使用 erb 模板,我猜你就是这样,那么你需要使用 erb 语法来调用辅助方法。你试过了吗:

      <body class="<%= background_type %>">
      

      ?

      【讨论】:

      • 感谢您的回答。但实际上我使用的是haml,我给出的视图示例只是为了演示场景。我会解决的,谢谢。
      • 酷。很高兴你明白了!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多