Using ActiveRecord for tables that aren't named as plurals

99封情书 提交于 2019-12-25 01:20:03

问题


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:

  1. 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.

  2. Your table needs to have its primary key on an integer column called id with the auto increment property.

  3. 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


回答1:


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!



来源:https://stackoverflow.com/questions/11318725/using-activerecord-for-tables-that-arent-named-as-plurals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!