views:

28

answers:

1

Hello!

In my Rails app I have models that look something like this:

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

What I'm having problem with now is finding all comments under a specific blog. Can anyone see a solution to this?

Best regards, Erik

A: 

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

get all comments

comments=[]
Blog.first.posts.each do |post|
  comments = comments | post.comments
end
Bohdan Pohorilets
Thanks, I know about this solution. The problem though is that it'd require me to first get all posts and then loop through them all. I'd rather find a method where I can get them through SQL…
Erik