Anb*_*n p 8 entity ruby-on-rails ruby-on-rails-3 grape-api
我想在葡萄实体文件中有多个类,这是文件夹结构app/api/proj/api/v2/entities/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
Run Code Online (Sandbox Code Playgroud)
在Grape API中
present @committees, with: PROJ::API::V2::Entities::Committee
Run Code Online (Sandbox Code Playgroud)
工作中.但如果我在场
present @committees, with: PROJ::API::V2::Entities::CommitteeList
Run Code Online (Sandbox Code Playgroud)
它不起作用.但是当我将它移动到一个名为committee_list.rb实体内部的新文件时,它会起作用.
您似乎错过了帖子中的一些关键信息,因为您没有定义一个名为CommitteeList或CommitteeBase任何地方的类.我假设您已经定义了它们并且您没有提供该代码.
您遇到的问题与Rails如何自动加载类有关.在其他地方有更多 可用的信息,但基本上你应该确保你的类名,模块名,目录名和文件名都匹配.将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
Run Code Online (Sandbox Code Playgroud)
请注意,在此示例中,我重命名了一些内容; 您的类名应该是单数(committee不是committees),文件名应该与它们匹配,但进行此更改可能会导致您的应用中出现其他问题.通常,您应该使用单数而不是复数.
我建议您阅读常量和自动加载的Rails指南条目以获取更多详细信息.
更新:
在你的要点中,你说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
Run Code Online (Sandbox Code Playgroud)
您收到此错误,因为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及其所有类".