Rails 3 and Controller Instance Variables Inside a Helper

六眼飞鱼酱① 提交于 2020-02-05 07:37:53

问题


I just encounter a problem similar to http://www.ruby-forum.com/topic/216433

I need to access controller instance variable from helper.

Here is the code I have done, and it's not work.

Controller:

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

Helper:

module ApplicationHelper

  def background_type
    @background_type || 'default'
  end

end

Layout:

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

回答1:


After some searching. I got one solution from

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

and the Controller becomes:

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

and remove the method from ApplicationHelper. It's work for this scenario, but I'm still curious,

is there a way to access controller instance variable for method in ApplicationHelper?




回答2:


If you're using erb templates, which I'm guessing you are, then you need to use erb syntax to call the helper method. Have you tried:

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

?



来源:https://stackoverflow.com/questions/5208689/rails-3-and-controller-instance-variables-inside-a-helper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!