Reputation: 2019
I'm trying to get a basic rails app to read data out of a MS SQL Server database. In the tutorial I'm reading (snipped below), it mentions that the tables need to follow certain rules, such as the name being a pluralized and underscored, etc etc. None of the tables in my database follow that convention and that can't be changed. Is this still true? If so, what do I need to read to understand how to communicate with such tables?
SNIPPET http://coding.smashingmagazine.com/2009/03/27/ultimate-beginners-guide-to-ruby-on-rails/
Mappings between the structure and behavior of your models and the tables in the database are fully automated mostly, provided that you adhere to a few rules in the design of your tables. The general principles are:
Your table name is the pluralized, underscored variant of your classname. So, a class User would be mapped to the table users.CookieRecipe would be mapped to cookie_recipes.
Your table needs to have its primary key on an integer column called id with the auto increment property.
Associations to other tables are stored in columns that are named after them. If you want to store posts belonging to a user, the posts table would need a user_id column
Upvotes: 0
Views: 258
Reputation: 7304
First, assume you have some other database system underpinning your rails app, and you just need to add in read only access to the SQLServer database.
First create a master model in app/models/rosql.rb:
def Rosql < ActiveRecord::Base
establish_connection("ROSQL#{Rails.env}")
end
Then add this to your database.yml
ROSQLproduction:
adapter: sqlserver
mode: dblib
dataserver: WHATEVER
username: user
password: password
database: WHATEVER
port: 1433
That last part is actually highly dependent on the stack you use to access SQL Server. Above is an example of my particular choice, which is TinyTDS/Freetds. Regardless, now you can start declaring SQL Server table models like so:
SqlServerTable < Rosql
self.table_name = "non_railsy_table_name"
end
You may or may not want to try and define the primary key:
SqlServerTable < Rosql
self.table_name = "non_railsy_table_name"
self.primary_key "thingKey_PK"
end
So now, assume thingKeyPK is a string!
@x = SqlServerTable.find("XYZ123")
will work!
Upvotes: 3