2012-05-23 49 views
4

我試圖製作一個「通用模型」,以便它可以連接到任何數據庫的任何表。首先,我做了這個類,它會連接到指定(不使用模式),另一個數據庫在Ruby on Rails 3中製作通用模型時遇到的問題

Db的

class Db < ActiveRecord::Base 

    self.abstract_class = true 

    attr_accessor :error 

    def initialize(item = nil) 
     @error = "" 
     connect 
     super 
    end 

    def connect 
     could_connect = true 
     @error = "" 

     begin 
      ActiveRecord::Base.establish_connection(
       :adapter => "mysql2", 
       :host  => "localhost", 
       :username => "root", 
       :password => "", 
       :database => "another_database", 
       :port => 3306, 
       :encoding => "utf8" 
      ) 
     rescue ActiveRecord::ConnectionNotEstablished 
      @error = "Could not connect to database. The connection was not established" 
      could_connect = false 
     rescue Mysql2::Error 
      @error = "Could not connect to database using MySQL2" 
      could_connect = false 
     rescue => e 
      @error = "Could not connect to database. #{e.message}." 
      could_connect = false 
     end 

     return could_connect 
    end 

end 

於是,我做了這個類從數據庫繼承並指定表名

Gmodel

class Gmodel < Db 

    def initialize(new_table_name) 
     ActiveRecord::Base.set_table_name(new_table_name) 
     super 
    end 

end 

最後,在控制器

MainController

class MainController < ApplicationController 

    def index 
    @users = Gmodel.new("users") 
    end 

end 

但是,它gaves我這個錯誤:

undefined method `stringify_keys' for "users":String 

出了什麼問題?有沒有更好的方法來做到這一點?提前致謝!

+0

什麼是抽象類DB的目的是什麼? – sailor

+0

你曾經是一名Java開發人員嗎? –

回答

12

爲什麼不簡單create an ActiveRecord::Base subclass在運行時避免所有的麻煩?

t = 'some_table' 
c = Class.new(ActiveRecord::Base) { self.table_name = t } 

然後c指AR類some_table,你可以做平常的事情:

o = c.find(1) 
# 'o' is now a wrapper for the row of some_table where 'id = 1' 

cols = c.columns.map(&:name) 
# 'cols' is now an array of some_table's column names 

這是哪裏的Ruby類對象了。

如果您需要連接到另一個數據庫,那麼你可以把establish_connection呼叫塊隨着self.table_name

t = 'some_table' 
d = 'some_other_database' 
c = Class.new(ActiveRecord::Base) do 
    establish_connection(:adapter => 'mysql2', :database => d, ...) 
    self.table_name = t 
end 
+0

非常感謝,真棒! – pablomarti

+0

這看起來非常像我可以用來解決[這個問題](http://stackoverflow.com/questions/10729289/tableless-model-with-activerecord-associations-in-rails-3-2) - 會大大感謝你能否看看並給我一些建議? –

+1

Rails 4不支持匿名ActiveRecord類:https://github.com/rails/rails/issues/8934 –