Ruby on Rails: Fully functional tableless model

后端 未结 2 1155
时光说笑
时光说笑 2021-01-19 02:09

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


        
2条回答
  •  逝去的感伤
    2021-01-19 02:19

    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
    

提交回复
热议问题