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

Pau*_*way 4 ruby activerecord model ruby-on-rails

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

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
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

错误.

Pau*_*way 7

我在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
Run Code Online (Sandbox Code Playgroud)

  • 是否可以使用与ActiveModel的关系?has_one,has_many等.无法弄清楚如何用AM做到这一点. (2认同)

Tom*_*mek 5

或者你可以这样做(仅限 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
Run Code Online (Sandbox Code Playgroud)

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