助手中的 Rails 3 和控制器实例变量 [英] Rails 3 and Controller Instance Variables Inside a Helper
本文介绍了助手中的 Rails 3 和控制器实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚遇到一个类似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.
控制器:
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 %>">
推荐答案
经过一番搜索.我从
http://api.rubyonrails.org/classes/ActionController/Helpers/类方法.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 中删除该方法.它适用于这种情况,但我仍然很好奇,
and remove the method from ApplicationHelper. It's work for this scenario, but I'm still curious,
有没有办法访问 ApplicationHelper 中方法的控制器实例变量?
is there a way to access controller instance variable for method in ApplicationHelper?
这篇关于助手中的 Rails 3 和控制器实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文