Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ActiveRecord在类加载时将关系表作为枚举实例加载_Ruby On Rails_Ruby_Activerecord_Enums - Fatal编程技术网

Ruby on rails ActiveRecord在类加载时将关系表作为枚举实例加载

Ruby on rails ActiveRecord在类加载时将关系表作为枚举实例加载,ruby-on-rails,ruby,activerecord,enums,Ruby On Rails,Ruby,Activerecord,Enums,我有一个包含产品查找的关系数据库表。此表支持多个系统,其中只有一个是Rails应用程序。在Rails应用程序中,我想使用product lookup作为ActiveRecord类,其实例成员使用产品代码——例如,key code字段是一个4位字母数字。如果能够通过如下代码引用实例,那就太好了:ProductCode.01A3。当然,我不想简单地在Rails代码中声明它们,因为DB是多个系统的记录系统。另外,Ruby对不存在的产品代码有何反应?如果ProductCode.ABCD不存在,它是否只是

我有一个包含产品查找的关系数据库表。此表支持多个系统,其中只有一个是Rails应用程序。在Rails应用程序中,我想使用product lookup作为ActiveRecord类,其实例成员使用产品代码——例如,key code字段是一个4位字母数字。如果能够通过如下代码引用实例,那就太好了:ProductCode.01A3。当然,我不想简单地在Rails代码中声明它们,因为DB是多个系统的记录系统。另外,Ruby对不存在的产品代码有何反应?如果ProductCode.ABCD不存在,它是否只是默默地返回一个nil,而我需要在任何地方进行nil检查?还有一个问题是在生产中发布新的ProductCode。更新表需要重新加载类实例变量


想法?这能做到吗?应该这样做吗?我搜索过一个库,但可能我的Google fu没有那么好。

查找表是减少数据库查询数量的一个很好的工具,我经常在长的工作进程中使用它们。我不建议在webapp中使用它们,除非数据经常被访问,很少改变,而且获取成本很高

我为您解决的问题的实现如下所示:

class ProductCode
  @product_codes = {}
  class << self
    attr_accessor :product_codes
  end

  def self.get(code)
    @product_codes[code.to_s]
  end

  def self.cache_all
    # whatever you do here
    @product_codes = {'01A3' => 42}
  end
end

ProductCodes.cache_all

ProductCodes.get('01A3')
class产品代码
@乘积_码={}
类42}
结束
结束
ProductCodes.cache\u all
ProductCodes.get('01A3')