2012-04-21 55 views
9

我使用ruby和activerecord獲取有關mysql表的信息。我可以從模型中獲取表格,列和類型信息嗎?

我希望我可以直接從我的模型類獲得這些信息,這可能嗎?

說我有我的模型:

class Product < ActiveRecord::Base 
end 

是現在我能夠獲得相關的信息:

1. mysql table 
2. columns 
3. column types 

還是我必須從某個地方更深入地瞭解ActiveRecord的模塊來得到這個?

回答

20
  1. Product.table_name
  2. Product.column_names
  3. Product.columns_hash['title'].type
+0

如果你使用3.與'id' 'Product.columns_hash [「id」] .type'給你':integer' 有沒有辦法將它轉換成一個'Integer'? – mariowise 2014-07-31 18:50:34

+0

'Product.columns_hash [「id」]。type.to_s.classify.constantize' – 2016-07-25 14:32:34

2

看一看ActiveRecord::ModelSchema::ClassMethods

class Product < ActiveRecord::Base 
    self.table_name # 1 
    self.columns # 2 
    self.columns_hash['name'].type # 3 
end 
+0

你肯定是最後一個? Docs說'columns'是一個數組,而不是散列。 – jdoe 2012-04-21 22:02:00

+0

對不起,你是對的 - 我糾正了它。 – DanS 2012-04-21 22:07:05