Ruby on Rails: Fully functional tableless model

后端 未结 2 1153
时光说笑
时光说笑 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
    
    0 讨论(0)
  • 2021-01-19 02:24

    Or you could do it like this (Edge Rails only):

    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
    

    By simply including ActiveModel::Model you get all the other modules included for you. It makes for a cleaner and more explicit representation (as in this is an ActiveModel)

    0 讨论(0)
提交回复
热议问题