Rails 3.2 中具有 ActiveRecord 关联的无表模型 [英] Tableless model with ActiveRecord associations in Rails 3.2

查看:20
本文介绍了Rails 3.2 中具有 ActiveRecord 关联的无表模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序配置包括一些需要在 AR 关系中使用的值.我知道这是一个奇怪且潜在的犯罪行为,但我需要将配置作为文本文件进行维护,老实说,我认为我有一个很好的无表模型案例.不幸的是,我无法说服 AR(Rails 3.2)不要寻找表格.我的无桌模型:

My application configuration includes some values which need to be used in AR relationships. I'm aware this is an odd and potentially criminal thing to attempt, but I need to maintain the configuration as a textfile, and I honestly think I have a good case for a tableless model. Unfortunately I'm having trouble convincing AR (Rails 3.2) not to look for the table. My tableless model:

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

这一切都基于 此处在 SO其他地方,但唉,我得到SQLException:没有这样的表:东西:任何线索任何人?

This is all based on code found here on SO and elsewhere, but alas, I get SQLException: no such table: stuffs: Any clues any one?

推荐答案

对于 Rails >= 3.2 有 activerecord-tableless gem.它是创建无表 ActiveRecord 模型的瑰宝,因此它支持验证、关联、类型.

For Rails >= 3.2 there is the activerecord-tableless gem. Its a gem to create tableless ActiveRecord models, so it has support for validations, associations, types.

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

When you are using the recommended way (using ActiveModel opposed to ActiveRecord) to do it in Rails 3.x there is no support for association nor types.

这篇关于Rails 3.2 中具有 ActiveRecord 关联的无表模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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