Tableless model in rails 3.1

前端 未结 6 1667
小蘑菇
小蘑菇 2021-02-04 17:04

Looks like this method doesn\'t work anymore in rails 3.1. So, does someone have a working solution?

Actually, I\'ve found this gist. It solves problems with colum

6条回答
  •  走了就别回头了
    2021-02-04 17:42

    This tableless thing seems more and more sort of a hack, but the mix just isn't the same thing (don't remember exactly what didn't work now, I've dealt with it some months ago, returned to it because upgrade to 3.1 broke it). The 3.1.0rc4 version worked with 'columns_hash' method override, the 3.1.0 requires also a 'column_defaults' override. So here's a version that passes my project tests.

    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
    
      def self.columns_hash
        @columns_hash ||= Hash[columns.map { |column| [column.name, column] }]
      end
    
      def self.column_names
        @column_names ||= columns.map { |column| column.name }
      end
    
      def self.column_defaults
        @column_defaults ||= columns.map { |column| [column.name, nil] }.inject({}) { |m, e| m[e[0]] = e[1]; m }
      end
    
      # Override the save method to prevent exceptions.
      def save(validate = true)
        validate ? valid? : true
      end
    end
    

    Hope it works for you,

    -- José

提交回复
热议问题