型号:
class Thread < ActiveRecord::Base
has_many :threaded, :through => :threaded, :foreign_key => :thread_id
class ThreadFeed < ActiveRecord::Base
belongs_to :threaded, :polymorphic => true
模型字段
Thread (id)
ThreadFeed (id, thread_id, threaded_id, threaded_type)
问题在于:
@thread.threaded
Rails使用(threaded_id,threaded_type)作为外键,我希望thread_id是外键。
答案 0 :(得分:0)
看看这个Railscast,Polymorphism
它将使您更好地了解多态性的工作原理。
我注意到的第一个问题是它应该通过:threadfeed,而不是:threaded
class Thread < ActiveRecord::Base
has_many :threadfeeds, :as => :threaded
在Railscast中,他有:
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Article < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Photo < ActiveRecord::Base
has_many :comments, :as => :commentable
#...
end
class Event < ActiveRecord::Base
has_many :comments, :as => :commentable
end
答案 1 :(得分:0)
第一个问题是Thread不知道什么是feed:
class Thread < ActiveRecord::Base
has_many :feeds, :through => :thread_feeds, :as => :feeded
has_many :thread_feeds
class ThreadFeed < ActiveRecord::Base
belongs_to :feeded, :polymorphic => true
第二个问题是多态的复杂性。这是一篇很棒的文章:http://blog.hasmanythrough.com/2006/4/3/polymorphic-through