ActiveRecord::Base Without Table

前端 未结 7 1444
灰色年华
灰色年华 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:23

    This is an approach I have used in the past:

    In app/models/tableless.rb

    class Tableless < ActiveRecord::Base
      def self.columns
        @columns ||= [];
      end
    
      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
    
      # Override the save method to prevent exceptions.
      def save(validate = true)
        validate ? valid? : true
      end
    end
    

    In app/models/foo.rb

    class Foo < Tableless
      column :bar, :string  
      validates_presence_of :bar
    end
    

    In script/console

    Loading development environment (Rails 2.2.2)
    >> foo = Foo.new
    => #<Foo bar: nil>
    >> foo.valid?
    => false
    >> foo.errors
    => #<ActiveRecord::Errors:0x235b270 @errors={"bar"=>["can't be blank"]}, @base=#<Foo bar: nil>>
    
    0 讨论(0)
提交回复
热议问题