views:

54

answers:

1

Hello!

My models look something like this:

Section

has_and_belongs_to_many :blogs

Blog

has_and_belongs_to_many :sections

has_many :posts

Post

belongs_to :blog

I can get all Posts from a certain Section's Blog by doing this:

section.blogs[n].posts

My question though is how to get all Posts connected to a Section (via a Blog)? I e something like:

section.blogs.posts

or event sweeter would be:

section.posts

Thank you!

+1  A: 

You want something like:

Section
has_and_belongs_to_many :blogs
has_many :posts, :through => :blogs

I'm not certain the syntax is exactly correct, but the through attribute is what you are looking for.

macabail
Sadly this raises the exception:Mysql::Error: Unknown column 'blogs.section_id' in 'where clause': SELECT count(*) AS count_all FROM `posts` INNER JOIN `blogs` ON `posts`.blog_id = `blogs`.id WHERE ((`blogs`.section_id = 1))
Erik
@Erik - You have to set up your models/tables slightly differently when using has many through as opposed to has and belongs to many. Check out the docs: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
Jimmy Cuadra
@Jimmy Cuadra: Do you mean I should abandon the has_and_belongs_to_many in favor for has_many :through?
Erik
@jimmy, thanks for posting the doc link, should help clear that up.
macabail
@erik, it depends; are blogs and sections really co-dependent, or is it that blogs belong to a section, and a section has_many blogs ?
macabail
@Erik - Yes, you use one or the other. The basic rule of thumb is to always use has many through unless you're sure you will never need to work with the join model directly.
Jimmy Cuadra
@macabail: A section can have many blogs and a blog can also have many sections, so as I see it there must be some kind of join table.
Erik
@Jimmy Cuadra: Ok, thank you, I'll give it a go!
Erik
@Erik: did that work out for you?
macabail