在Rails的3.2 ActiveRecord关联无表格模型 [英] Tableless model with ActiveRecord associations in Rails 3.2

查看:211
本文介绍了在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

这是由实际的模型扩展:

This is extended by the actual model:

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

这是所有基于code发现这里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?

推荐答案

有关滑轨> = 3.2还有就是 的ActiveRecord-无表格 宝石。它是一种宝石创建无表格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.

当您使用的是推荐的方法(使用加载ActiveModel反对的ActiveRecord)做它的Rails 3.x中存在的关联,也没有类型不支持。

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天全站免登陆