本文介绍了Rails的:存储像ActiveRecords静态数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找的宝石和/或实现静态存储器相似ActiveRecords而不是基于数据库的插件一段时间。让我们把这个类NonDBRecord。它应具有以下性质:

 类Foo< NonDBRecord
  方法add_item('A',:property1 =>一些价值:property2 =>更多的价值)
  方法add_item(B:property1 =>一些价值:property2 =>更多的价值)
结束

班巴≤;的ActiveRecord :: Base的
  belongs_to_nondbrecord:FOO,:将class_name => '富'
结束

#NonDBRecord自动声明常量
[富:: A,富:: B]

#NonDBRecord是枚举
Foo.all#返回[美孚:: A,富:: B]

#NonDBRecord是基于身份
Bar.create(:foo_id =>富:: A.id)

#...所以你可以通过它搜索
X = Bar.find(:第一,:条件=> {:foo_id =>富:: A.id})

#...和存储,检索,且通过它的id实例
x.foo#返回美孚::一个
 

我想过简单地使用ActiveRecords(和数据库存储),但我不感觉良好。另外我不得不周围的一些预先加载的问题与ActiveRecord的解决方案脚尖。任何帮助将是AP preciated之前,我开始写我自己的解决方案。

修改

这些记录,目的是要枚举。例如,假设你正在做一个纸牌游戏。我希望能够像做

 类卡< NonDBRecord
  attr_reader:西装,:指数
结束
类游戏
  belongs_to的:wild_card,:将class_name => '卡'
结束
 

解决方案

我想说加载ActiveModel是你所期待的。它配备了Rails 3和封装所有来自ActiveRecord的东西,如验证,序列化和各种各样的。有一个瑞安贝茨 railscast 在这个问题上。希望这有助于!

I've been looking for a while for gems and/or plugins that implement static storage similar ActiveRecords but is not database-based. Let's call this class NonDBRecord. It should have the following property:

class Foo < NonDBRecord
  add_item('a', :property1 => 'some value', :property2 => 'some more value')
  add_item('b', :property1 => 'some value', :property2 => 'some more value')
end

class Bar < ActiveRecord::Base
  belongs_to_nondbrecord :foo, :class_name => 'Foo'
end

# NonDBRecord declare constants automatically
[ Foo::A, Foo::B ]

# NonDBRecord is enumerable
Foo.all # returns [Foo::A,Foo::B]

# NonDBRecord is id-based
Bar.create(:foo_id => Foo::A.id)

# ...so you can search by it
x = Bar.find(:first, :conditions => { :foo_id => Foo::A.id })

# ...and is stored, retrieved, and instantiated by its id
x.foo # returns Foo::A

I've thought about simply using ActiveRecords (and database storage), but I don't feel good about it. Plus I've had to tip-toe around some eager loading problems with the ActiveRecord solution. Any help would be appreciated before I start writing my own solution.

edit

These records are meant to be enumerations. For example, let's say you're making a card game. I want to be able to do something like

class Card < NonDBRecord
  attr_reader :suit, :index
end
class Game
  belongs_to :wild_card, :class_name => 'Card'
end
解决方案

I would say ActiveModel is what you are looking for. It comes with Rails 3 and encapsulates all kind of goodies from ActiveRecord, such as Validation, Serialization and sorts. There is a Ryan Bates railscast on that issue. Hope this helps!

这篇关于Rails的:存储像ActiveRecords静态数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 21:14