[英]How can I use SQL Server Table Views as Rails Models (Read Only)?
I'm using SQL Server as my database for my Rails project. 我将SQL Server用作Rails项目的数据库。 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.
但是,在Rails控制台中,我没有得到预期的结果。 The only example that gives back some correct information is when I do a
count
on the object as shown in Example 3 below. 唯一提供正确信息的示例是当我对对象进行
count
时,如下面的示例3所示。
I'm using the following gems to connect to my SQL Server: 我正在使用以下gems连接到我的SQL Server:
gem 'tiny_tds'
gem 'activerecord-sqlserver-adapter'
Also I have installed freetds-dev 0.91-6build1 我也安装了freetds-dev 0.91-6build1
Example 1 例子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.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 例子3
2.2.2 :008 > Game.count
(4.7ms) EXEC sp_executesql N'SELECT COUNT(*) FROM [games]'
=> 12541
incoming_model.rb 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 game_model.rb
class Game < IncomingModel
self.table_name = 'games'
end
database.yml database.yml的
incoming_development:
<<: *default
adapter: sqlserver
host: games-data
port: 1433
database: Incoming
username: ****
password: ****
pool: 5
timeout: 15000
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. 我还必须为我的需要添加gem
composite_primary_keys
,这可能超出了某些开发人员的需求。 Thanks to anyone that took the time to try and help troubleshoot this issue! 感谢所有花时间尝试解决此问题的人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.