2017-04-15 7 views
8

하나의 파일에있는 각 개체,이 폴더 구조 응용 프로그램/API/PROJ/API/V2/단체/committees.rb입니다포도 나 포도 엔티티 파일 내의 여러 클래스를 갖고 싶어

module PROJ::API::V2::Entities 
class Committee < Grape::Entity 
expose :id 

expose :name, :full_name, :email, :tag, :parent_id 

expose :country do |entity, option| 
    entity.parent.name if entity.parent.present? 
end 

# include Urls 

private 
    def self.namespace_path 
    "committees" 
    end 
end 

    class CommitteeWithSubcommittees < CommitteeBase 
     # include ProfilePhoto 
     expose :suboffices, with: 'PROJ::API::V2::Entities::CommitteeBase' 
     end 

내부 Grape API

present @committees, with: PROJ::API::V2::Entities::Committee 

이 작동 중입니다. 하지만 만약 내가 함께한다면

present @committees, with: PROJ::API::V2::Entities::CommitteeList 

그것은 작동하지 않습니다. 하지만 엔티티 내부에 committee_list.rb이라는 새 파일로 이동하면 작동합니다.

답변

5

어디서나 CommitteeList 또는 CommitteeBase이라는 클래스를 정의하지 않았기 때문에 게시물의 주요 정보가 누락 된 것 같습니다. 나는 당신이 그것들을 정의했고 그 코드를 제공하지 않았다고 가정한다.

Rails가 클래스를 자동로드하는 방법과 관련하여 문제가 있습니다. 여기에 more informationavailable elsewhere이 있지만 본질적으로 클래스 이름, 모듈 이름, 디렉토리 이름 및 파일 이름이 모두 일치하는지 확인해야합니다. CommitteeList 클래스를 자신의 파일로 옮길 때 그 이유는 레일스가 클래스를 동적으로 찾을 수 있기 때문입니다.

나는 당신이 제공 한 내용에 따라 몇 가지 추측-일을 했어,하지만 당신은 다음과 같습니다 뭔가 싶어 :이 예에서 나는 몇 가지 이름을 변경 한 것을

# app/api/proj/api/v2/entities/committee.rb 
module PROJ::API::V2::Entities 
    class Committee < Grape::Entity; end 
end 

# app/api/proj/api/v2/entities/committee_base.rb 
module PROJ::API::V2::Entities 
    class CommitteeBase; end 
end 

# app/api/proj/api/v2/entities/committee_with_subcommittee.rb 
module PROJ::API::V2::Entities 
    class CommitteeWithSubcommittee < CommitteeBase; end 
end 

# app/api/proj/api/v2/entities/committee_list.rb 
module PROJ::API::V2::Entities 
    class CommitteeList < CommitteeBase; end 
end 

참고; 클래스 이름은 단수이어야하며 (committeecommittees) 파일 이름이 일치해야합니다.하지만 변경하면 앱에 다른 문제가 발생할 수 있습니다. 일반적으로 you should use singular과 복수가 아닙니다.

자세한 내용은 the Rails guide entry on constants and autoloading을 읽어 보시기 바랍니다.

업데이트 : 레일 만라는 이름의 클래스를 찾습니다 때문에

# app/api/proj/api/v2/entities/committee_base.rb 
module PROJ::API::V2::Entities 
    class CommitteeBase < Grape::Entity; 
    expose :id 
    end 
    class CommitteeOffice < CommitteeBase; 
    expose :name 
    end 
end 

당신이 오류를 얻을 : 당신의 요점에서

당신이 다음 코드로 present @committees, with: PROJ::API::V2::Entities::CommitteeOffice를 실행할 때 Uninitialized constant PROJ::API::V2::Entities::CommitteeOffice를 얻을 수 있다고 파일 entities/committee_base.rbPROJ::API::V2::Entities::CommitteeBase. 엔티티 클래스에 하나의 모 놀리 식 파일을 사용하려면 위 파일의 이름을 app/api/proj/api/v2/entities.rb으로 지정해야합니다.

파일 이름을 app/api/proj/api/v2/entities.rb으로 지정하면 레일즈는 "이 파일에는 모듈 Entities과 그 모든 클래스가 들어 있습니다."라고 알려줍니다. 파일 구조와

+0

의 나를 위해 잘 작동하지만이 같은 구조를 가지고있는 경우는 작동하지 https://gist.github.com/anbublacky/a6e66217b2fcdeb52fe580864beecf7f –

+0

업데이트 요점은 요점을 기반으로 –

+0

업데이트 답을 확인하세요 – anothermh