2010-08-17 71 views
1

在我的Rails應用程序我有模型,看起來像這樣:多態assosciation問題

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 

什麼我在與現在在一個特定的博客找到所有評論的問題。任何人都可以看到這個解決方案?

最好的問候, 埃裏克

+0

你是如何試圖找到評論?你能爲我們發佈代碼嗎?如果您在控制檯中收到錯誤消息,那麼錯誤消息是什麼? – sosborn 2010-08-18 07:50:33

+0

我不明白你爲什麼要使用多態關聯? – Bohdan 2010-08-18 08:45:32

+0

你好! 我正在使用多形態assosciation,因爲在將來我想允許評論其他對象比帖子... – Erik 2010-08-19 10:50:45

回答

0

嗨首先連接

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 
+0

謝謝,我知道這個解決方案。但問題是,它需要我先獲取所有帖子,然後循環瀏覽所有帖子。我寧願找到一種方法,我可以讓他們通過SQL ... – Erik 2010-08-19 10:51:43