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

时间:2012-05-23 23:31:09

标签: ruby-on-rails activerecord model

我的应用程序配置包括一些需要在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 << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
  end

  def self.columns_hash
    @columns_hash ||= Hash[columns.map { |column| [column.name, column] }]
  end

  def self.column_names
    @column_names ||= columns.map { |column| column.name }
  end

  def self.column_defaults
    @column_defaults ||= columns.map { |column| [column.name, nil] }.inject({}) { |m, e| m[e[0]] = e[1]; m }
  end

  def self.descends_from_active_record?
    return true
  end

  def persisted?
    return false
  end

  def save( opts = {} )
    options = { :validate => true }.merge(opts)
    options[:validate] ? valid? : true
  end
end

这是由实际模型扩展的:

class Stuff < Tableless

  has_many :stuff_things
  has_many :things, :through => :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

这完全取决于找到的代码here on SOelsewhere,但是,我得到 SQLException:没有这样的表:东西:任何一个线索?

2 个答案:

答案 0 :(得分:3)

对于Rails&gt; = 3.2,有activerecord-tableless个宝石。它是创建无表格ActiveRecord模型的宝石,因此它支持验证,关联,类型。

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

答案 1 :(得分:1)

对于Rails&gt; = 4,您还可以通过定义像这样的无表格类来获得对验证,关联和一些回调(如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