问题
I work on a team that is using ActiveRecord to access the schema on a MSSQL server. Modifying the schema is not an option and the column names have spaces in them, a la SPACEY COLUMN
.
When writing the ActiveRecord class to access a table with spaces in it, what is good practice?
We also need this to work with factory girl...
回答1:
AR-JDBC (as well as the AR-SQLServer-Adapter) will/should handle this just fine since it auto-magically quotes column name identifiers using "[ COlumn NAME ]" ... I personally would hide this from bubbling up as much as possible e.g. using aliases :
class MySpacey < ActiveRecord::Base
set_table_name 'SPACEY TABLE'
set_primary_key 'MY ID'
alias_attribute :id, :'MY ID'
end
回答2:
Consider User
is the Model and User Name
is the column you need to access.
User.where('User Name' => 'Bob')
You can add multiple conditions also,
User.where('User Name' => 'Bob', 'Email Address' => 'sample@sample.com')
You can also try,
User.where('[User name] = ? AND [Email Address] = ?', 'Bob', 'sample@sample.com')
And if your table itself has space in it. Try,
class User < ActiveRecord::Base
self.table_name = "user table"
end
来源:https://stackoverflow.com/questions/22206018/using-activerecord-with-column-names-with-spaces-in-them