0

현재 데이터 마이그레이션 및 문제가 발생했습니다. 마이그레이션 파일에이 파일이 있습니다.레일스 5에서 마이그레이션 모델이 작동하지 않음

class DropTutorProfileTable < ActiveRecord::Migration[5.1] 
    class Subject < ActiveRecord::Base 
    has_and_belongs_to_many :tutor_accounts 
    end 

    class TutorAccount < ActiveRecord::Base 
    has_and_belongs_to_many :subjects 
    end 

    def change 
    send_data_to_subject_tutor_account 
    drop_table :tutor_profiles 
    end 

    private 

    def send_data_to_subject_tutor_account 
    TutorProfile.all.find_each do |tutor_profile| 
     # data migration code here 
     tutor_account.subjects << subject 
    end 
    end 
end 

이 마이그레이션을 실행할 때 다음 오류가 발생합니다.

StandardError: An error has occurred, this and all later migrations canceled: 

Subject(#70181814234340) expected, got #<DropTutorProfileTable::Subject id: 3, name: "Writing", academic_type: "academic"> which is an instance of DropTutorProfileTable::Subject(#70181808133400) 

이 문제를 처음으로 다루고 있습니다. 마이그레이션에서 모델을 정의하고 문제가없는 다른 마이그레이션을 수행했습니다. 흥미롭게도, 때의 출력 TutorAccount 인스턴스의 클래스와 Subject 인스턴스의 클래스, 내가 얻을 ...

TutorAccount 
DropTutorProfileTable::Subject 

여기에 무슨 일이 일어나고 있는지 모른다. 당신의 도움은 대단히 감사합니다!

+0

'TutorAccount' 클래스가 프로젝트의 다른 위치에 정의되어 있지만 중첩되지 않은 클래스를 다시 확인할 수 있습니까? – Shiko

+0

'tutor_profile'의 주제를'tutor_account'에 할당하려고합니까? 당신의 마지막 질문 인 "interesting">이 마이그레이션 내에서'Subject' 클래스를 정의하고 있기 때문에'DropTutorProfileTable'과 함께 네임 스페이스가됩니다. – inveterateliterate

+0

또한 의존하지 않고'TutorProfileSubject'와 같은 조인 테이블을 명시 적으로 생성 할 것을 권장합니다 'has_and_belongs_to_many'에. 왜 그것이 권장 접근법인지에 대한 몇 가지 훌륭한 예가 있습니다. – inveterateliterate

답변

0

그래서이 문제에 대한 해결책을 찾았습니다. 문제는 이전 중에 클래스의 인스턴스가 호출되는 방식이었습니다. 마이그레이션 코드에서 마이그레이션에 정의 된 모델을 직접 호출 할 때 마이그레이션을 위해 네임 스페이스가 지정됩니다. 예를 들면. Subject 클래스가 이전에 정의되어 있으며 자신의 개체로 호출되고 있기 때문에

class DropTutorProfileTable < ActiveRecord::Migration[5.1] 
    class Subject < ActiveRecord::Base; end 

    def change 
    Subject.new.class # Returns DropTutorProfileTable::Subject 
    TutorProfile.subject.class # Returns Subject 
    end 
end 

이 의미가 있습니다. 그러나 연관된 주체의 클래스는 코드베이스에 정의되어 있고 마이그레이션이 아니라 Subject 클래스로 정의됩니다. 평범한 루비를 이해한다면 분명히 드러나는 행동입니다. 실제로이 코드를 예제로 실행했고 내 논문의 유효성을 확인했습니다. @inveterateliterate와 @Shiko에게 올바른 방향으로 나를 가르쳐 주셔서 감사합니다.

관련 문제