2014-07-22 1 views
1

Google 검색을 수행 한 후에도 SQLite로 작업 할 때 Rails가 추가 한 기본 키를 무시할 수있는 성공적인 방법을 찾을 수 없습니다.레일 4와 SQLite에서 기본 키 열을 재정의

class CreateRequests < ActiveRecord::Migration 
    def change 
     create_table :requests, id: false do |t| 
      t.string :id 
      t.string :name 
     end  
    end 
end 

위의 코드는 기본 id 기본 키를 추가하지 레일을 알려줍니다 지금까지 나는 다음과 같은 기본 마이그레이션을 가지고있다. 대신 id 문자열을 사용하고 싶습니다.

SQLite의 ALTER 명령의 제한으로 문제가 발생합니다.이 명령은 테이블을 만든 후에 기본 키를 추가 할 수 없습니다. 나는이 출력 얻을 rake db:migrate를 실행 한 후

class CreateRequests < ActiveRecord::Migration 
    def change 
     create_table :requests, id: false do |t| 
      t.string :id 
      t.string :name 
     end  

     adapter_type = connection.adapter_name.downcase.to_sym  
     case adapter_type 
      when :postgresql 
       # TODO 
      when :sqlite   
       execute <<-SQL   
        DROP TABLE requests; 
        CREATE TABLE requests (id TEXT NOT NULL PRIMARY KEY, name TEXT); 
       SQL 
      else 
       raise NotImplementedError, "Unknown adapter type '#{adapter_type}'" 
      end 

    end 
end 

: 따라서, 나는이 해결 방법을 시도했다가 모든 것을 확인했다 보이지만, 그래서

== 20140722082104 CreateRequests: migrating =================================== 
-- create_table(:requests, {:id=>false}) 
    -> 0.0010s 
-- execute("   DROP TABLE requests;\n   CREATE TABLE requests (id 
    TEXT NOT NULL PRIMARY KEY, name TEXT);\n") 
    -> 0.0010s 
== 20140722082104 CreateRequests: migrated (0.0030s) ========================== 

을 나는 SQLite는 관리 프로그램과 데이터베이스 파일을 검사 할 때, 테이블 requests가 존재하지 않습니다.

내가 뭘 잘못하고 있니? 고맙습니다.

답변

2

OK, 나는 나 자신에 대한 해결책을 발견했습니다 : 특별히 때,

execute "DROP TABLE requests;" 
execute "CREATE TABLE requests (id TEXT NOT NULL PRIMARY KEY, name TEXT);" 

편집

손으로 테이블을 생성 방지하기 위해 더 우아한 해결책 : 독립적으로 각 SQL 문 실행 테이블에 여러 열이 있고 ActiveRecord의 create_table 메서드 호출과 동기화 된 상태로 유지하려고합니다.

#Get from SQLite's master table the SQL statement that creates the table, 
#and that was initially generated by Rails 
sql = select_value("SELECT sql FROM sqlite_master WHERE type='table' AND name='requests'") 

#Only replace the definition of the 'id' column by adding the PRIMARY KEY 
#constraint 
sql.gsub!(/"id" [^,]+/, '"id" VARCHAR(255) NOT NULL PRIMARY KEY')  

#Delete the original table    
drop_table :requests 

#Create the table again 
execute sql