Using ActiveRecord with column names with spaces in them

亡梦爱人 提交于 2019-12-12 00:56:15

问题


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

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