加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在Ruby on Rails中制作通用模型时出现的问题3

发布时间:2020-12-17 04:04:54 所属栏目:百科 来源:网络整理
导读:我正在尝试制作一个“通用模型”,以便它可以连接到任何数据库的任何表.首先,我创建了这个连接到另一个指定数据库的类(不使用模式) D b class Db ActiveRecord::Base self.abstract_class = true attr_accessor :error def initialize(item = nil) @error = "
我正在尝试制作一个“通用模型”,以便它可以连接到任何数据库的任何表.首先,我创建了这个连接到另一个指定数据库的类(不使用模式)

D b

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

然后,我创建了这个继承自Db的类并指定了表名

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

但是,它给我带来了这个错误:

undefined method `stringify_keys' for "users":String

可能有什么不对?有没有更好的方法来做到这一点?提前致谢!

解决方法

为什么不在运行时简单地使用 create an ActiveRecord::Base subclass并避免所有麻烦?

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

然后c指的是some_table的AR类,你可以做通常的事情:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读