1

我正在用 Ruby 和 Grape 构建一个 Web API。我有两个相互需要的类,这会导致出现未初始化的常量类错误的情况。我得到错误的地方是在连接器的实体类中,请参见下面的示例代码,它需要 Card::Entity 在初始化之前。有没有办法在不将实体定义移动到另一个文件的情况下解决这个问题?

#card.rb
require_relative 'connector'
require_relative 'caption'

class Card < ActiveRecord::Base

  belongs_to  :medium
  belongs_to  :storyline

  has_many    :connectors, autosave: true
  has_many    :connected_cards, class_name: "Connector", foreign_key: "connected_card_id"
  has_many    :captions

  accepts_nested_attributes_for :connectors, :captions

  class Entity < Grape::Entity
    expose :id, documentation: { readonly: true }
    expose :cardtype
    expose :connectors, using: Connector::Entity
    expose :captions, using: Caption::Entity
  end
end

#connector.rb
require_relative 'card'

class Connector < ActiveRecord::Base
  has_one  :card
  has_one  :connected_card, :class_name => "Card", :foreign_key => "connected_card_id"

  class Entity < Grape::Entity
    expose :id, documentation: { readonly: true }
    expose :title
    expose :card, using: Card::Entity
    expose :connected_card, using: Card::Entity
  end
end
4

1 回答 1

2

我对葡萄知之甚少,但这可以通过“预先声明”类来解决:

#card.rb
require_relative 'caption'

class Connector < ActiveRecord::Base
  # empty declaration just to make the import works
end

class Card < ActiveRecord::Base
  belongs_to  :medium
  belongs_to  :storyline

  has_many    :connectors, autosave: true
  has_many    :connected_cards, class_name: "Connector", foreign_key: "connected_card_id"
  has_many    :captions

  accepts_nested_attributes_for :connectors, :captions
  ...
end

不过,我认为 QPaysTaxes 在这里可能有关于设计的有效观点。

于 2015-05-02T14:44:56.310 回答