Rails 3.2中具有ActiveRecord关联的无表模型

我的应用程序配置包括一些需要在AR关系中使用的值。 我知道这是一个奇怪的,可能是犯罪的尝试,但我需要将配置保持为文本文件,老实说,我认为我有一个无表格模型的好例子。 不幸的是,我无法说服AR(Rails 3.2)不要寻找表格。 我的无表款式:

class Tableless < ActiveRecord::Base def self.table_name self.name.tableize end def self.columns @columns ||= []; end def self.column(name, sql_type = nil, default = nil, null = true) columns < true }.merge(opts) options[:validate] ? valid? : true end end 

这是由实际模型扩展:

 class Stuff  :stuff_things column :id, :integer column :name, :string column :value, :string def initialize(attributes = {}) attributes.each do |name, value| send("#{name}=", value) end end end 

这完全基于SO和其他地方的代码,但是,我得到了SQLException:没有这样的表:东西:任何一个线索?

对于Rails> = 3.2,有activerecord-tableless gem。 它是创建无表格ActiveRecord模型的gem,因此它支持validation,关联,类型。

当您使用推荐的方式(使用与ActiveRecord相对的ActiveModel)在Rails 3.x中执行此操作时,不支持关联或类型。

对于Rails> = 4,您还可以通过定义像这样的无表格类来获得对validation,关联和一些回调(如after_initialize)的支持:

 class Tableless < ActiveRecord::Base def self.columns() @columns ||= []; end def self.column(name, sql_type = nil, default = nil, null = true) columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null) end attr_accessor :id, :name, :value has_many :stuff_things has_many :things, :through => :stuff_things end