Ruby on Rails:全function无表格模型

在搜索无表格模型示例后,我遇到了这个代码,这似乎是关于如何创建一个代码的一般共识。

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 

但是我还希望它能够像模型那样起作用,代表一个对象的集合,这样我就可以做Item.all。

计划是使用文件填充项目,并从文件中提取每个项目的属性。

但是目前如果我做Item.all我会得到一个

Mysql2::Error Table 'test_dev.items' doesn't exist...

错误。

我在http://railscasts.com/episodes/219-active-model找到了一个例子,我可以使用模型特征,然后覆盖所有的静态方法(之前应该考虑过这个)。

 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 

或者你可以这样做(仅限Edge Rails):

 class Item include ActiveModel::Model 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 end 

通过简单地包含ActiveModel :: Model,您可以获得包含的所有其他模块。 它使得表示更清晰,更明确(因为这是一个ActiveModel)