Ruby on rails 对MSSQL的Rails选择查询返回-1:Fixnum

Ruby on rails 对MSSQL的Rails选择查询返回-1:Fixnum,ruby-on-rails,database,ruby-on-rails-3,sql-server-2008,Ruby On Rails,Database,Ruby On Rails 3,Sql Server 2008,我将Rails连接到外部MSSQL数据库。在database.yml中,适配器是sqlserver 查询的代码为: class External < ActiveRecord::Base def self.select_all_entries external_connection_hash = configurations["external_DB"] establish_connection external_connection_hash c

我将Rails连接到外部MSSQL数据库。在database.yml中,适配器是sqlserver

查询的代码为:

class External < ActiveRecord::Base
   def self.select_all_entries
      external_connection_hash = configurations["external_DB"]
      establish_connection external_connection_hash
      con = connection()

      side = con.execute("Select * from dbo.BBOrders").fetch_row;
      return side
   end
end

您不需要设置模型类来建立数据库连接

在database.yml中定义您的数据库,去掉类External,当您使用rails s或rails c加载rails时,ActiveRecord::Base将建立连接

在database.yml中,您告诉active record您正在使用sqlserver适配器,这意味着您应该在gem文件中包含此gem:

在Rails中定义模型类的惯例是将其定义为资源。您的表名为dbo.BBorders。有点奇怪的名字,它应该只是BBU订单或订单。那么您的型号名称是:

class BbOrder < ActiveRecord::Base
  #pay attention to capitalization and singularity/plurality
  #convention is for table name be the plural, camel cased version of the model name
  #BbOrder is the model name. bb_orders is the table name
end
如果确实要编写自定义查询,可以使用:

BbOrder.connection.execute("<whatever arbitrary sql you want")
或者更复杂的事情:

BbOrder.where(:shipped => true)
will generate:
"select bb_orders.* from bb_orders where shipped"
and this will return collection of BbOrder instances where the attribute shipped is true
in other words, a row in the database where the shipped column is true 
corresponds to one BbOrder instance

我想你需要一颗宝石。DBI ODBC驱动器可能是许多可用选项之一。但请尝试此URL上的说明

最终结果将是这样的

需要“dbi” 将MY_DSN替换为ODBC数据的名称 来源将和dbusername替换为dbpassword 您的数据库登录名和密码。 连接'DBI:ODBC:MY_DSN','dbusername','dbpassword'do | dbh| 用数据库中的表名替换mytable。 胸径。从mytable的do行中选择所有的select*| p行 终止 终止

这是您应用程序的主要数据库吗?或者这是您试图建立连接的辅助数据库?它是我的主数据库。但这会有什么改变?你从中得到了什么帮助吗?我不理解这种命名惯例。我的表必须命名为BBOrders。那么这是否意味着我不能使用rails?我是否在models文件夹中创建bb_orders.rb并复制该类?并且您的代码假设我正在连接默认的sqlite db。我有一个外部的。如何将其与代码联系起来?您仍然可以使用rails,在models/bb_order.rb文件中命名您的模型类BbOrdersclass BbOrder < ActiveRecord::Base self.table_name = "dbo.BBOrders" end
BbOrder.all

ActiveRecord will generate the query:
"select * from bb_orders" (or whatever the table name is)
BbOrder.connection.execute("<whatever arbitrary sql you want")
BbOrder.find(45)
will generate:
"select bb_orders.* from bb_orders where id = 45"
and this will return an instance of your BbOrder class.
BbOrder.where(:shipped => true)
will generate:
"select bb_orders.* from bb_orders where shipped"
and this will return collection of BbOrder instances where the attribute shipped is true
in other words, a row in the database where the shipped column is true 
corresponds to one BbOrder instance