Ruby on Rails: Fully functional tableless model

后端 未结 2 1156
时光说笑
时光说笑 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: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)

提交回复
热议问题