如何为一项特定操作定义 Rails Helper?
我有一个带有自定义 label_tag
方法的 LabelTagHelper,但我只在新建、创建、编辑 和更新操作。
有没有办法只为特定操作定义这个助手?类似于 helper :label_tag, :only => [:新建、:创建、:更新、:销毁]
?或者在 before_filter 中调用 self.class.helper :label_tag 是安全的吗?
I have a LabelTagHelper with a custom label_tag
method, but I only need this method in my new, create, edit and update actions.
Is there a way to define this helper only for a specific action? Something like helper :label_tag, :only => [:new, :create, :update, :destroy]
? Or it is safe to call self.class.helper :label_tag
in a before_filter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个,
有一个像这样的帮助器方法(在我的例子中,我使用了一个名为“ProjectsHelper”的帮助器)
这正在工作......希望这就是您所需要的,
欢呼
HTH
Sameera
注意:抱歉没有更新现有答案。由于这是全新的方法,因此考虑将其作为单独的答案
try this,
Have a helper method like this (in my case i used a helper called 'ProjectsHelper')
This is working... hope this is what you need,
cheers
HTH
sameera
NOTE: sorry for not updating the existing answer. Since this is completely new approach thought of having it as a separate answer
Rails 助手应该只是格式化程序。将其视为装饰表示层(视图)的函数,
因此将助手设置为 :before_filter 没有任何意义。由于控制器的操作通常涉及一些服务器端处理。
因此,您可以随时致电您的助手。因此无需仅为特定操作添加助手。正如我之前提到的,助手和控制器/模型操作应该是互斥的
,顺便说一句,您能否详细说明您的要求,为什么要限制您的助手
HTH
Sameera
rails Helpers should be just formatters. Think of it just as functions that will decorate your presentation layer (view)
So having helpers as :before_filter doesn't make any sense. As controllers actions often involves some server side processing.
So call your helper as and when you want. So there is no need to add helpers only for a specific action. as I mentioned earlier helpers and controller/ model actions should be mutually exclusive
BTW, could you elaborate your requirement, why you want to restrict your helper
HTH
sameera