2016-11-15 128 views
1

我想通过以下命令来访问表结构:Rails的控制台抛出错误

ActiveRecord::Base.connection.table_structure("projects") 

控制台引发以下错误:

NoMethodError: protected method `table_structure' called for # < ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x6559050>

我想知道Rails控制台是如何工作的,这个错误背后的原因是什么?有什么方法可以通过Rails控制台访问表结构,而不是经常切换到Sqlite3来检查模式?

回答

1

要打电话给你希望你的CA一起去的方法:

ActiveRecord::Base.connection.send(:table_structure, "projects") 

但我认为更好的办法是使用columns_hash获取有关表结构的最详细的信息:

Get the columns for a table as a hash, key is the column name value is the column object.

Project.columns_hash 

用法:假设您想获得有关id列的信息:

Project.columns_hash['id'] 
#=> #<ActiveRecord::ConnectionAdapters::PostgreSQLColumn:0x007fda9e48ce90 
# @array=false, 
# @cast_type=#<ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Integer:0x007fda9bda2e88 @limit=nil, @precision=nil, @range=-2147483648...2147483648, @scale=nil>, 
# @default=nil, 
# @default_function="nextval('users_id_seq'::regclass)", 
# @name="id", 
# @null=false, 
# @sql_type="integer"> 

也有columns

Returns an array of column objects for the table associated with this class.

column_names

Returns an array of column names as strings.

Project.columns 
Project.column_names 

full list of methods in documentation

+0

'NoMethodError:未定义的方法 'table_structure' 为#'使用发送 –

+0

@Deepak OP使用SQLite3 :) –

+0

ahh。好的明白了.. –

1

您可以通过只输入型号名称

在你的情况

Project 

这将返回类似直接将结构:

class Project < ActiveRecord::Base { 
      :id => :integer, 
     :name => :string, 
    :created_at => :datetime, 
    :updated_at => :datetime 
} 
+0

您能解释为什么这种方法不起作用吗? –

+0

它说在错误本身'table_structure'是一个受保护的方法 –

+1

@Kartikey我展示了如何调用你需要的方法,还有替代方法 –