如何将 SQL 服务器 Table 视图用作 Rails 模型(只读)?

How can I use SQL Server Table Views as Rails Models (Read Only)?

我正在使用 SQL 服务器作为我的 Rails 项目的数据库。我正在尝试创建一些模型以用于 3rd 方数据库并且只想从此数据库中读取。所以我查看了 table 我想为其创建一个对象,然后我想将我的活动记录模型指向它。但是,在 rails 控制台中,我没有得到预期的结果。返回一些正确信息的唯一示例是当我对对象执行 count 时,如下面的示例 3 所示。

我正在使用以下 gem 连接到我的 SQL 服务器:

gem 'tiny_tds'
gem 'activerecord-sqlserver-adapter'

我还安装了 freetds-dev 0.91-6build1

示例 1

2.2.2 :004 > Game.all
  Game Load (268.7ms)  EXEC sp_executesql N'SELECT [games].* FROM [games]'
 => #<ActiveRecord::Relation [#<Game >, #<Game >, #<Game >, #<Game >, #<Game >, #<Game >, #<Game >, #<Game >, #<Game >, #<Game >, ...]> 

示例 2

2.2.2 :001 > Game.first
  SQL (1.1ms)  USE [Incoming]
  Game Load (1.8ms)  EXEC sp_executesql N'SELECT  [games].* FROM [games] OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY'
TinyTds::Error: Incorrect syntax near '0'.: EXEC sp_executesql N'SELECT  [games].* FROM [games] OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY'
ActiveRecord::StatementInvalid: TinyTds::Error: Incorrect syntax near '0'.: EXEC sp_executesql N'SELECT  [games].* FROM [games] OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY'
    from /home/daveomcd/.rvm/gems/ruby-2.2.2/gems/activerecord-sqlserver-adapter-4.2.3/lib/active_record/connection_adapters/sqlserver/database_statements.rb:336:in `each'
    ...
    ...

示例 3

2.2.2 :008 > Game.count
   (4.7ms)  EXEC sp_executesql N'SELECT COUNT(*) FROM [games]'
 => 12541 

incoming_model.rb

class IncomingModel < ActiveRecord::Base
  self.abstract_class = true
  self.table_name_prefix = "Incoming.dbo."
  establish_connection "incoming_#{Rails.env}".to_sym
end

game_model.rb

class Game < IncomingModel
  self.table_name = 'games'
end

database.yml

incoming_development:
  <<: *default
  adapter: sqlserver
  host: games-data
  port: 1433
  database: Incoming
  username: ****
  password: ****
  pool: 5
  timeout: 15000

所以我发现我需要为 table 指定一个主键。所以这是我做的补充。

class Game < IncomingModel
  self.table_name = 'games'
  self.primary_key = 'game_id', 'this_other_column'
end

为了满足我的需要,我还必须合并 gem composite_primary_keys,但是,这可能比某些开发人员需要的更多。感谢所有花时间尝试帮助解决此问题的人!