1

Ruby と Grape で Web API を構築しています。互いに必要とする 2 つのクラスがあり、初期化されていない定数クラス エラーが発生する状況につながります。エラーが発生する場所は、Connector の Entity クラスにあります。初期化される前に 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 に答える