Ruby on Rails:功能齐全的无表模型 [英] Ruby on Rails: Fully functional tableless model

查看:22
本文介绍了Ruby on Rails:功能齐全的无表模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

不过,我也希望它能够像模型一样发挥作用,表示对象的集合,以便我可以执行 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::Error Table 'test_dev.items' 不存在...

错误.

推荐答案

我在 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屋!

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