ActiveRecord::Base Without Table

前端 未结 7 1478
灰色年华
灰色年华 2020-12-01 01:40

This came up a bit ago ( rails model attributes without corresponding column in db ) but it looks like the Rails plugin mentioned is not maintained ( http://agilewebdevelopm

7条回答
  •  伪装坚强ぢ
    2020-12-01 02:14

    I figure the more answers the better since this is one of the first results in google when searching for "rails 3.1 models without tables"

    I've implements the same thing without using ActiveRecord::Base while including the ActiveRecord::Validations

    The main goal was to get everything working in formtastic, and below I've included a sample payment that will not get saved anywhere but still has the ability to be validated using the validations we all know and love.

    class Payment
      include ActiveModel::Validations
      attr_accessor :cc_number, :payment_type, :exp_mm, :exp_yy, :card_security, :first_name, :last_name, :address_1, :address_2, :city, :state, :zip_code, :home_telephone, :email, :new_record
    
      validates_presence_of :cc_number, :payment_type, :exp_mm, :exp_yy, :card_security, :first_name, :last_name, :address_1, :address_2, :city, :state
    
      def initialize(options = {})
        if options.blank?
          new_record = true
        else
          new_record = false
        end
        options.each do |key, value|
          method_object = self.method((key + "=").to_sym)
          method_object.call(value)
        end
      end
    
      def new_record?
        return new_record
      end
    
      def to_key
      end
    
      def persisted?
        return false
      end
    end
    

    I hope this helps someone as I've spent a few hours trying to figure this out today.

提交回复
热议问题