繁体   English   中英

Ruby on Rails:全功能无表格模型

[英]Ruby on Rails: Fully functional tableless model

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM