现有的Rails的模型,而无需从数据库中获取它 [英] Existing Rails model without fetching it from the database

查看:133
本文介绍了现有的Rails的模型,而无需从数据库中获取它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道,如果它可以创建一个模型实例和应用的ID和其他属性,而不必从数据库中加载了吗?我试图这样做,但协会是不会从数据库:(任何想法牵强?

Does anyone know if its possible to create a model instance and apply the ID and any other attributes without having to load it from the database? I tried doing this, but the associations are not fetched from the database :( Any ideas?

修改

我想做到的是简单:

  1. 从数据库读取现有记录。
  2. 在存储为散列输出记录到的Redis或其他存储器存储。
  3. 当记录获取下一次,第一次获取缓存的商店,如果找不到,则转到步骤1。
  4. 如果有一个高速缓存命中,然后加载所有缓存的属性到该模型并进行了模型实例表现为好像它是一个模型,从与有限组列的数据库中获取的。

这是我在哪里卡住了,我一直在做的是创造一个Model.new对象,并手动设置每一个PARAMS的。这工作,但它把实例化的模型对象作为一个新的记录。目前已经得到了在ActiveRecord的中间子程序,做属性设置。

This is where I am stuck, what I've been doing is creating a Model.new object and setting each of the params manually. This works, but it treats the instantiated model object as a new record. There has got to be an intermediate subroutine in ActiveRecord that does the attribute setting.

推荐答案

我通过执行以下操作解决了这个问题。

I solved the problem by doing the following.

  1. 创建一个新模式类继承我想要的模型类已经被缓存到内存中。

  1. Create a new model class which extends the model class that I want to have cached into memory.

新类的table_name的设置为相同的一个是父类

Set the table_name of the new class to the same one as the parent class.

创建一个新的初始化方法,调用超级方法,然后让该方法的参数,以便包含父类的所有属性的哈希变量。

Create a new initialize method, call the super method in it, and then allow a parameter of that method to allow for a hash variable containing all the properties of the parent class.

重载方法 new_record?并将其设置为使协会的工作。

Overload the method new_record? and set that to false so that the associations work.

下面是我的code:

class Session < User

  self.table_name = 'users'

  METHODS = [:id, :username] # all the columns that you wish to have in the memory hash
  METHODS.each do |method|
    attr_accessor method
  end

  def initialize(data)
    super({})

    if data.is_a?(User)
      user = data
      data = {}
      METHODS.each do |key|
        data[key] = user.send(key)
      end
    else
      data = JSON.parse(data)
    end

    data.each do |key,value|
      key = key.to_s
      self.send(key+'=',value)
    end
  end

  def new_record?
    false
  end

end

这篇关于现有的Rails的模型,而无需从数据库中获取它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆