ActiveRecord::Base Without Table

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

    UPDATE: For Rails 3 this can be done very easy. In Rails 3+ you can use the new ActiveModel module and its submodules. This should work now:

    class Tableless
      include ActiveModel::Validations
    
      attr_accessor :name
    
      validates_presence_of :name
    end
    

    For more info, you can check out the Railscast (or read about it on AsciiCasts) on the topic, as well as this blog post by Yehuda Katz.

    OLD ANSWER FOLLOWS:

    You may need to add this to the solution, proposed by John Topley in the previous comment:

    class Tableless
    
      class << self
        def table_name
          self.name.tableize
        end
      end
    
    end
    
    class Foo < Tableless; end
    Foo.table_name # will return "foos"
    

    This provides you with a "fake" table name, if you need one. Without this method, Foo::table_name will evaluate to "tablelesses".

提交回复
热议问题