1

source_typeRailshas_many through polymorphicアソシエーション内でランタイムを定義する方法はありますか?

以下のコードはあなたに簡単なアイデアを与えるはずです..しかしそれは機能していません..何か提案はありますか??

class A < ...
  has_many :message_messagables, :foreign_key => :message_id

  has_many :messagables, :through => :message_messagables, :source => :messagable, :source_type => lambda { |a| a.custom_type }

 def custom_type
   raise "needs to be defined inside subclass"
 end

end


class MessageMessagable < ... 
 belongs_to :messagable, :polymorphic => true #[C, D]
 belongs_to :message
end

class B < A

 def custom_type
   "C"
 end
end

class E < A
 def custom_type
   "D"
 end

end
4

1 に答える 1

2

私は同じ問題に遭遇しました。使用可能なすべてのソースタイプを一覧表示して解決し、ディスパッチメソッドを追加しました。

class A < ...
  has_many :message_messagables, :foreign_key => :message_id

  # list all source types as association
  %w(email file).each do |source_type|
    has_many source_type.pluralize.to_sym, :through => :message_messagables, :source => :messagable, :source_type => source_type
  end

  # dispatch methodk
  def messagables
    public_send custom_type.pluralize.to_sym
  end
end
于 2013-04-27T12:26:45.143 に答える