如何在 Rails 3 中创建 ActiveRecord 无表模型 [英] How to create ActiveRecord tableless Model in Rails 3
本文介绍了如何在 Rails 3 中创建 ActiveRecord 无表模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个 Active Record 无表模型.我的 user.rb 看起来像这样
I am trying to create a Active Record tableless Model. My user.rb looks like this
class User < ActiveRecord::Base
class_inheritable_accessor :columns
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
column :name, :text
column :exception, :text
serialize :exception
end
在控制器中创建新对象时
When creating the new object in controller
@user = User.new
@user = User.new
我收到错误
Mysql2::Error: Table 'Sampledb.users' 不存在:SHOW FIELDS FROM users
Mysql2::Error: Table 'Sampledb.users' doesn't exist: SHOW FIELDS FROM users
推荐答案
class Tableless
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
def self.attr_accessor(*vars)
@attributes ||= []
@attributes.concat( vars )
super
end
def self.attributes
@attributes
end
def initialize(attributes={})
attributes && attributes.each do |name, value|
send("#{name}=", value) if respond_to? name.to_sym
end
end
def persisted?
false
end
def self.inspect
"#<#{ self.to_s} #{ self.attributes.collect{ |e| ":#{ e }" }.join(', ') }>"
end
end
这篇关于如何在 Rails 3 中创建 ActiveRecord 无表模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文