从User.rb模型访问ApplicationHelper [英] Accessing ApplicationHelper from User.rb model
问题描述
以下一些不起作用的简单代码:
Here's some simple code that isn't working:
module ApplicationHelper
def industries
industries = ['Agriculture','Food', etc.]
end
end
class User < ActiveRecord::Base
include ApplicationHelper
validates_inclusion_of :industries, :in => ApplicationHelper.industries
...
end
使用undefined method 'industries'
运行用户操作时,此代码失败.您知道我怎样才能正确地引用帮助者(或者最好是行业)吗?
This code is failing when a user action is run with undefined method 'industries'
. Do you know how I can reference the helper (or preferably just industries) the right way?
基于下面Mauricio的答案中的代码,如何在控制器和视图中访问INDUSTRIES
?我在使行业无处不在时确实遇到了麻烦,但这确实需要针对我的应用程序.
Based on the code in Mauricio's answer below, how can INDUSTRIES
be accessed in a controller and a view? I'm having real trouble making industries accessible everywhere, but it really needs to be for my application.
推荐答案
您应该从不执行此类操作.不应将ApplicationHelper包含在模型中.最好的解决方案是:
You should never do something like this. ApplicationHelper is not supposed to be included in a model. Best solution would be:
class User < ActiveRecord::Base
INDUSTRIES = ['Agriculture','Food']
validates_inclusion_of :industries, :in => INDUSTRIES
end
module ApplicationHelper
def industries
User::INDUSTRIES
end
end
现在,您可以通过一种简单而又不错的方式来完成它.
And now you have it done in a simple and nice way.
编辑
您需要访问任何行业的任何地方:
Anywhere you need to access industries you should use:
User::INDUSTRIES
就是这样.
这篇关于从User.rb模型访问ApplicationHelper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!