简体   繁体   English

Rails:如何从帮助器访问模型

[英]Rails: how can I access a Model from a Helper

I have a constant defined in a Model, and need access to it from within a Helper. 我在模型中定义了一个常量,需要在Helper中访问它。 Is there a way to do this? 有没有办法做到这一点? Example: 例:

#app/models/my_model.rb
class MyModel < ActiveRecord::Base
  VALUE = 3

  def self.get_value
    VALUE
  end
end

#app/helpers/users_helper.rb
module UsersHelper
  VALUE_V1 = MyModel.get_value
  VALUE_V2 = MyModel::VALUE
end

Both VALUE_V1, and VALUE_V2 fail for me (uninitialized constant). VALUE_V1和VALUE_V2都对我失败(未初始化的常量)。

You need to use top level namespace when referring a constant inside module. 引用模块内部的常量时,需要使用顶级名称空间。

So, 所以,

 value1 = ::MyModel.get_value

Also, as Vimsha commented you can use the constant directly, no need to define another constant. 另外,正如Vimsha所说,您可以直接使用常量,而无需定义另一个常量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM