Ruby on Rails的:全功能无表格模型 [英] Ruby on Rails: Fully functional tableless model
问题描述
寻找一个无表格的典范后,我碰到这个code这似乎是对如何创建一个普遍的共识。
After searching for a tableless model example I came across this code which seems to be the general consensus on how to create one.
class Item < ActiveRecord::Base
class_inheritable_accessor :columns
self.columns = []
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 all
return []
end
column :recommendable_type, :string
#Other columns, validations and relations etc...
end
不过我也喜欢它的功能,作为一种模式呢,再presenting对象的集合,这样我可以做Item.all。
However I would also like it to function, as a model does, representing a collection of object, so that I can do Item.all.
该计划是为了填充文件的项目,每个项目的属性会从文件中提取的。
The plan is to populate Items with files and each Item's properties will be extracted from the files.
不过现在如果我这样做Item.all我收到了
However currently if I do Item.all I get a
Mysql2 ::错误表test_dev.items不存在...
错误。
推荐答案
我找到了一个例子,在<一个href="http://railscasts.com/episodes/219-active-model">http://railscasts.com/episodes/219-active-model在那里我可以用模型特征,然后覆盖静态方法都一样(之前应该已经想到了这一点)。
I found an example at http://railscasts.com/episodes/219-active-model where I can use model features and then override static methods like all (should have thought of this before).
class Item
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name, :email, :content
validates_presence_of :name
validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
validates_length_of :content, :maximum => 500
class << self
def all
return []
end
end
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
这篇关于Ruby on Rails的:全功能无表格模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!