如何在“有很多通过”多态关联中定义运行时source_type?

时间:2012-07-18 13:59:33

标签: ruby-on-rails activerecord model-associations

有没有办法在rails source_type has_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

1 个答案:

答案 0 :(得分: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
相关问题