1

これが私が考えていることです:

class Widget < ActiveRecord::Base
  has_one :widget_layout
end

class WidgetLayout < ActiveRecord::Base
  belongs_to :widget
  belongs_to :layoutable, :polymorphic => true
end

class InformationalLayout < WidgetLayout
  has_one :widget_layout, :as => :layoutable
end

class OneWayCommunicationLayout < WidgetLayout
  has_one :widget_layout, :as => :layoutable
end

これは完全に間違っていると確信しています。私がやろうとしていることは、ポリモーフィックな関連性が示されているのを見たのとは逆のようです。たとえば、Railsガイドから:

class Picture < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true
end

class Employee < ActiveRecord::Base 
  has_many :pictures, :as => :imageable 
end 

class Product < ActiveRecord::Base 
  has_many :pictures, :as => :imageable 
end

ここで、「所有」モデル(製品または従業員)は、多くのクラスの1つになります。「所有」モデルを多くのクラスの1つにしたいと思います。これらはすべて、別のクラスから基本動作を継承します。さらに、これらのサブクラスの動作はすべて十分に異なるため、STIは非常に非効率的です。私はここでかなり迷っています...あなたが与えることができるどんな助けにも感謝します!

編集:私がやりたいことを明確にするために...私はWidgetと呼ばれる「所有」クラスを持っています。ウィジェットは、非常に単純なWebアプリに沿ったものを表します。各ウィジェットは、いくつかの異なるレイアウトの1つで表すことができます。したがって、これらの異なるレイアウトクラスを定義しています。レイアウトは、外観と動作の両方でかなり異なる可能性がありますが、いくつかの共通の機能を共有しています。このため、その一般的な動作をWidgetLayoutクラスに抽出して、そこから継承できるようにしたいと思います。結局、どのウィジェットも1つの「特定の」レイアウト(情報、OneWayCommunicationなど)に関連付けることができます。このセットアップをどのように構成する必要があるのか​​わかりません。

編集(最後のもの、私は願っています!):ああ、あなたの例をもう一度見て、私はそれを見る。私が見逃しているのは、レイアウトに一般的な動作を継承させることだけです。だから、このようなものはうまくいくでしょうか?:

class Widget < ActiveRecord::Base
  belongs_to :layout, :polymorphic => true
end

class InformationalLayout < WidgetLayout
  has_many :widgets, :as => :layout
end

class OneWayCommunicationLayout < WidgetLayout
  has_many :widgets, :as => :layout
end

class WidgetLayout < ActiveRecord::Base
  # Define common behaviour here
end
4

1 に答える 1

1

要件が投稿した例と一致しない理由はありますか?

class Widget < ActiveRecord::Base
  belongs_to :layout, :polymorphic => true
end

class InformationalLayout < DefaultLayout
  has_many :widgets, :as => :layout
end

class OneWayCommunicationLayout < DefaultLayout
  has_many :widgets, :as => :layout
end

def DefaultLayout < ActiveRecord::Base
 #no relationship here, only class inheritance 

  def get_sorted_data
    return 'example data'
  end
end

# eg
widget.find(1).layout.class => InformationalLayout
widget.find(2).layout.class => OneWayCommunicationLayout

widget.find(1).layout.get_sorted_data => 'example data'
widget.find(2).layout.get_sorted_data => 'example data'
于 2010-09-08T13:00:25.207 に答える