2017-04-15 165 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