【问题标题】:Ruby on Rails: Fully functional tableless modelRuby on Rails:功能齐全的无表模型
【发布时间】:2011-02-14 22:00:25
【问题描述】:

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

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...

错误。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord model


    【解决方案1】:

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

    【讨论】:

    • 是否可以使用与 ActiveModel 的关系? has_one、has_many 等。无法弄清楚如何使用 AM。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      • 2011-10-05
      相关资源
      最近更新 更多