我使用ruby和activerecord獲取有關mysql表的信息。我可以從模型中獲取表格,列和類型信息嗎?
我希望我可以直接從我的模型類獲得這些信息,這可能嗎?
說我有我的模型:
class Product < ActiveRecord::Base
end
是現在我能夠獲得相關的信息:
1. mysql table
2. columns
3. column types
還是我必須從某個地方更深入地瞭解ActiveRecord的模塊來得到這個?
我使用ruby和activerecord獲取有關mysql表的信息。我可以從模型中獲取表格,列和類型信息嗎?
我希望我可以直接從我的模型類獲得這些信息,這可能嗎?
說我有我的模型:
class Product < ActiveRecord::Base
end
是現在我能夠獲得相關的信息:
1. mysql table
2. columns
3. column types
還是我必須從某個地方更深入地瞭解ActiveRecord的模塊來得到這個?
Product.table_name
Product.column_names
Product.columns_hash['title'].type
看一看ActiveRecord::ModelSchema::ClassMethods:
class Product < ActiveRecord::Base
self.table_name # 1
self.columns # 2
self.columns_hash['name'].type # 3
end
如果你使用3.與'id' 'Product.columns_hash [「id」] .type'給你':integer' 有沒有辦法將它轉換成一個'Integer'? – mariowise 2014-07-31 18:50:34
'Product.columns_hash [「id」]。type.to_s.classify.constantize' – 2016-07-25 14:32:34