2017-04-15 98 views
8

我想里面有葡萄的实体文件中的多个类的每个实体,这是文件夹结构的应用程序/ API /凸出/ 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 

和内葡萄API

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

正在工作。但如果我与

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

这是行不通的。但是,当我将它移动到一个名为committee_list.rb的实体内部的新文件时它会起作用。

回答

5

您好像错过了您发布的关键信息,因为您尚未在任何地方定义名为CommitteeListCommitteeBase的类。我假设你已经定义了它们,并且你没有提供该代码。

您遇到的问题与Rails如何自动加载类有关。这里有more informationavailable elsewhere,但基本上你应该确保你的类名,模块名,目录名和文件名都匹配。当你将CommitteeList类移动到它自己的文件时,它的工作原因是因为Rails能够动态地找到这个类。

我不得不做根据您提供哪些猜测的工作,但你想要的东西,看起来像这样:

# 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 

注意,在这个例子中,我已经改名为一些事情;你的班级名称应该是单数(committee而不是committees),并且文件名应该与他们匹配,但是做出该更改可能会在您的应用程序中导致其他问题。一般来说,you should use singular而不是复数。

我建议您阅读the Rails guide entry on constants and autoloading了解更多详情。

更新时间:

在你要点你说你Uninitialized constant PROJ::API::V2::Entities::CommitteeOffice当您运行present @committees, with: PROJ::API::V2::Entities::CommitteeOffice用下面的代码:

# 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 

你得到这个错误,因为Rails会只认准指定的类PROJ::API::V2::Entities::CommitteeBase在文件entities/committee_base.rb中。如果您希望为您的实体类使用单个单一文件,那么您必须将上述文件命名为app/api/proj/api/v2/entities.rb

通过命名文件app/api/proj/api/v2/entities.rb,它告诉Rails“该文件包含模块Entities及其所有类。”

+0

随着文件结构的工作为我好,但如果我有结构这样它不工作https://gist.github.com/anbublacky/a6e66217b2fcdeb52fe580864beecf7f –

+0

更新要点请根据要点 –

+0

更新答案 – anothermh