views:

109

answers:

1

Hi, I'm using ActiveRecord in Ruby on Rails.

I have a table named documents(Document class) and I want to have another table data_documents(DataDocument) class which is effectively the same except for having different table name. In other words, I want two tables with the same behavior except for table name.

class DataDocument < Document
  #set_table_name "data_documents"
  self.table_name = "data_documents"
end

My solution was to use class inheritance as above, yet this resulted in inconsistent SQL statement for create operation where there are both 'documents' table and 'data_documents' table. Can you figure out why and how I can make it work?

>> DataDocument.create(:did=>"dd")
ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'data_documents.did' in 'where clause': SELECT `documents`.id FROM `documents` WHERE (`data_documents`.`did` = BINARY 'dd')  LIMIT 1
        from /Users/lifidea/.gem/ruby/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/abstract_adapter.rb:212:in `log'
        from /Users/lifidea/.gem/ruby/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/mysql_adapter.rb:320:in `execute'
        from /Users/lifidea/.gem/ruby/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/mysql_adapter.rb:595:in `select'
        from /Users/lifidea/.gem/ruby/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/abstract/database_statements.rb:7:in `select_all_without_query_cache'
        from /Users/lifidea/.gem/ruby/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/abstract/query_cache.rb:62:in `select_all'
A: 

I do not know the inner workings of ActiveRecord enough to tell you why this isn't working, but the simplest solution is to move the functionality from the Document class and place it into a DocumentMod Module. Then include that module in the Document class and in the DataDocument class that both inherit from ActiveRecord.

Example:

module DocumentsMod

  def self.included(klass)
    klass.extend ClassMethods
    klass.send(:include, InstanceMethods)
  end

 module ClassMethods
  class methods here ...
 end

 module InstanceMethods
  instance methods here...
 end
end

class Document < ActiveRecord::Base
  include DocumentMod
end

class DataDocument < ActiveRecord::Base
  include DocumentMod
end
ScottD