您无需设置 Model 类即可建立数据库连接。
在 database.yml 中定义您的数据库,去掉 External 类,ActiveRecord::Base 将在您加载 rails 时建立连接(使用 rails s 或 rails c)
在 database.yml 中,您告诉活动记录您正在使用 sqlserver 适配器,这意味着您的 Gemfile 中应该有这个 gem:https ://github.com/rails-sqlserver/activerecord-sqlserver-adapter
在 Rails 中定义模型类的惯例是将其定义为资源。您有一个名为 dbo.BBorders 的表名。有点奇怪的名字,它可能应该只是“bb_orders”或“orders”。那么您的型号名称是:
class BbOrder < ActiveRecord::Base
#pay attention to capitalization and singularity/plurality
#convention is for table name be the plural, camel cased version of the model name
#BbOrder is the model name. bb_orders is the table name
end
或者
class Order < ActiveRecord::Base
end
如果您的表名必须是“dbo.BBOrders”,那么您可以覆盖 Rails 期望的默认表名:
class BbOrder < ActiveRecord::Base
self.table_name = "dbo.BBOrders"
end
一旦你定义了一个模型并与一个表关联,你可以从控制台查询它:
BbOrder.all
ActiveRecord will generate the query:
"select * from bb_orders" (or whatever the table name is)
如果您真的想编写自定义查询,您可以使用:
BbOrder.connection.execute("<whatever arbitrary sql you want")
如果您尝试“获取一行”,那么您必须向它提供有关您尝试获取的行的一些信息:
BbOrder.find(45)
will generate:
"select bb_orders.* from bb_orders where id = 45"
and this will return an instance of your BbOrder class.
或更复杂的东西:
BbOrder.where(:shipped => true)
will generate:
"select bb_orders.* from bb_orders where shipped"
and this will return collection of BbOrder instances where the attribute shipped is true
in other words, a row in the database where the shipped column is true
corresponds to one BbOrder instance