現在做的一個項目中 project 和 life 分別要對應一個comments
首先在comment表中加入兩列
commentable_id, commentable_type
然后在project和life中分別設計連接關系
project:
has_many :comments, as: :commentable
life:
has_many :comments, as: :commentable
最后在comment中加入一個方法 find_commentable
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return @commentable = $1.classify.constantize.find(value)
end
end
end
=~ 是正則表達式的匹配
$1 為匹配的第一個括號里的值
參考
http://railscasts.com/episodes/154-polymorphic-association?view=asciicast
http://ruby-china.org/topics/2427