真实情况是这样的:
我有一个多态类 Channel, 定义如下
然后有3个类: User, Activity, Video 均会引用 channel, 其中 Video的定义如下:
使用 channel.video 是不行的,因为 channel 根本就不知道如何引用 video . 怎么办?
使用动态方法 method_missing
我有一个多态类 Channel, 定义如下
belongs_to :channelable, :polymorphic => true
然后有3个类: User, Activity, Video 均会引用 channel, 其中 Video的定义如下:
has_one :channel, :as => :channelable
使用 channel.video 是不行的,因为 channel 根本就不知道如何引用 video . 怎么办?
使用动态方法 method_missing
def method_missing(method_id, *arguments, &block)
match_name = read_attribute(:channelable_type).to_s.downcase
if method_id.to_s == match_name
self.channelable_type.downcase.capitalize.constantize.find_by_id(self.channelable_id)
elsif method_id.to_s == "#{match_name}_id"
self.channelable_id
else
super method_id, *arguments, &block
end
end