class User < ActiveRecord::Base
end
User.columns.each do |column|
puts column.name
puts column.type
...
puts column.?
end
是否能够通过 ActiveRecord 对象获取字段的备注?
module Utils
module MySQL
# 字段的备注字典
def column_comments
result = show_columns(self.column_names)
result.inject({}){|h, arr| h.merge(arr[0] => arr[8]) }.symbolize_keys
end
# 指定字段名的备注
def comment_of(field)
field = field.to_s
return "" unless self.column_names.include?(field)
result = show_columns(field)
result[0][8]
end
private
def show_columns(field)
condition_sql = if field.is_a?(Array)
"IN ('" + field.join("', '") + "')"
else
"= '#{field}'"
end
sql = "SHOW FULL COLUMNS FROM `#{self.table_name}` WHERE FIELD " << condition_sql
# 自行根据需求,进行修改
result = Rails.cache.fetch(sql) do
self.connection.execute(sql).to_a
end
end
end
end
unless ActiveRecord::Base.respond_to?(:column_comments)
ActiveRecord::Base.send :extend, Utils::MySQL
puts '_' * 88 + 'Utils::MySQL'
end
User.column_comments
#>
{
:id => '',
:username => '用户名'
}
User.comment_of(:username)
#> '用户名'
其实还是 sql,
偷懒的话呢,就用 migration_comments
,
这个 gem 写了 adapter,
这样调用就可以了
klass = User
column_comments = klass.connection.retrieve_column_comments(klass.table_name)
返回是 字段 => 解释 的 hash
了解 mysql 的 information_schema 表,你就知道最简单的查询方法了。
SELECT column_comment FROM information_schema.columns
WHERE table_schema = 'db_name'
AND table_name = 'table_name'
AND column_name = 'column_name'