2016-10-08 4 views
0

기존 앱에서 STI를 사용하여 확장 한 기본 모델의 값을 inheritance_column으로 변경하고 있습니다. 기존 열이 새로운 inheritance_column과 일치하도록하려면 어떻게 마이그레이션 할 수 있습니까?Rails inheritance_column migration

액티브 :: SubclassNotFound :

class MigrateStoryTypes < ActiveRecord::Migration 

    def self.up 
    Story.all.each { |story| 
     new_story_type = story.story_type.camelize + 'Story' 
     puts "changing #{story.id}'s story_type from #{story.story_type} to #{new_story_type}" 
     story.update_column :story_type, new_story_type 
    } 
    end 

    def self.down 
    Story.all.each { |story| 
     new_story_type = story.story_type.underscore.gsub /_story/, '' 
     puts "changing #{story.id}'s story_type from #{story.story_type} to #{new_story_type}" 
     story.update_column :story_type, new_story_type 
    } 
    end 

end 

그러나, 이것은 실패 :

여기 내 첫 번째 시도이다 'clean_slate'단일 테이블 상속 메커니즘 는 서브 클래스를 찾는 데 실패했습니다. 상속의 경우 'story_type'열이 클래스를 저장하기 위해 예약되어 있기 때문에이 오류는 으로 발생합니다. 상속 클래스를 저장하는 데 을 사용하지 않으려는 경우이 열의 이름을 바꾸거나 해당 정보에 다른 열을 사용하려면 Story.inheritance_column을 덮어 씁니다.

ActiveRecord를 통해이 작업을 수행하는 간단한 방법이 있습니까? 아니면 임시 열, SQL 등을 사용해야합니까?

+1

클래스 이름의 밑줄이 쳐진 버전 (예 :''clean_slate'')이 들어있는'story_type' 컬럼이 이미 있고 이것을 STI로 옮기고,'story_type'을 STI 컬럼으로 사용하고, 'story_type' 값을 클래스 이름에 적용 하시겠습니까? 얼마나 많은'story_type' 값을 가지고 있습니까? –

+0

@muistooshort 바로. 나는 현재'story_type' 값을 두 개 가지고 있습니다. – pdoherty926

답변

1

마이그레이션 중에 모델을 사용하는 것은 일반적으로 모델 클래스가 데이터베이스 구조가 무엇인지는 알고 있지만 마이그레이션은 데이터베이스 구조를 조작한다고 가정하기 때문에 나쁜 생각입니다. 오류 메시지는 모델 클래스가 데이터베이스와 동기화되지 않은 경우 중 하나입니다. Story.all이 모델을 인스턴스화하려고하자 ActiveRecord가 클래스 이름을 story_type에서 찾을 것으로 예상하지만 story_type에 이전 문자열 유형이 남아 있기 때문에 데이터베이스가 수정 될 때까지 모델을 사용하여 데이터베이스를 수정할 수 없습니다. 결정된.

모델이 마이그레이션 중에 존재하지 않는 것처럼 가장하는 것이 좋습니다. 데이터베이스를 직접 사용하는 경우 더 나은 시간을 가질 수 있습니다.

def up 
    connection.execute(%q{ 
    update stories 
    set story_type = case story_type 
     when 'whatever1' then 'Whatever1Story' 
     when 'whatever2' then 'Whatever2Story' 
    end 
    }) 
end 

두 값을가 그리고 당신은 그들이 그렇게 영리하려고 시간을 낭비하지 않는 무엇을 알고는 SQL은 매우 간단합니다, 그래서 당신은 두 개의 story_type 값이 있습니다.

+0

여기에 좋은 조언이 많이 있습니다. 감사! – pdoherty926