How can I use SQL Server Table Views as Rails Mode

2019-05-18 14:18发布

问题:

I'm using SQL Server as my database for my Rails project. I'm trying to create some models to use for a 3rd party database and only want to read from this database. So I made a view of the table I wanted to create an object for and then I wanted to point my active record model to it. However, in rails console I don't get back expected results. The only example that gives back some correct information is when I do a count on the object as shown in Example 3 below.

I'm using the following gems to connect to my SQL Server:

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

Also I have installed freetds-dev 0.91-6build1

Example 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 >, ...]> 

Example 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'
    ...
    ...

Example 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

回答1:

So I found that I needed to specify a primary key for the table. So here is the addition I made.

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

I also had to incorporate for my needs the gem composite_primary_keys, however, that might be more than what some developers will need. Thanks to anyone that took the time to try and help troubleshoot this issue!