2016-11-15 1 views
1

나는 다음과 같은 명령을 통해 테이블 ​​구조에 액세스하려고 :레일 콘솔 던지는 오류

:

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

콘솔은 다음과 같은 오류가 발생합니다

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

레일즈 콘솔의 작동 방식과이 오류의 원인은 무엇입니까? 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

아를 사용합니다. 알았어 .. –

1

당신은 직접 바로이 같은 반환

Project 

귀하의 경우에는 모델 이름

을 입력하여 구조를 얻을 수 있습니다 :

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

이 접근 방식이 작동하지 않는 이유를 설명해 주시겠습니까? –

+0

그것은 오류 자체에'table_structure'가 보호 된 메서드라고 말했습니다. –

+1

@Kartikey 필요한 메서드를 호출하는 방법과 대안을 보여주었습니다 –