多态关联问题

时间:2010-08-17 21:15:26

标签: ruby-on-rails ruby-on-rails-3 polymorphism

在我的Rails应用程序中,我的模型看起来像这样:

class Blog < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :blog
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

我现在遇到的问题是在特定博客下找到所有评论。任何人都可以看到解决方案吗?

祝你好运, 埃里克

1 个答案:

答案 0 :(得分:0)

Hi Firstly connections

class Blog < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :blog
  has_many :comments, :as=>:commentable #Post.first.comments or Blog.posts.first.comments
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

获取所有评论

comments=[]
Blog.first.posts.each do |post|
  comments = comments | post.comments
end