searching through belongs_to relations

Hey all,
I have a Topic and a Post model, topics have many posts and posts
belongs to a topic.
I would like to find all posts which topic name = 'xyz'. How could I do that?

those are my models attributes:

so I guess it would something like:
Post.find(:all,:conditions=> something with topic_id and smile )

thanx in advance


This is pretty simple unless I’m just completely missing your question.

Use the associations you’ve defined. Find by topic. Since topic has_many posts, that’s what you use.

@topic = Topic.find :first,

:conditions=>[‘ = ?’, “xyz”],


@post = @topic.posts

ok thanx,
and what if I have

Category has_many forums
Forum has_many topics which belongs to category
Topic has_many posts which belongs_to forum
Post which belongs_to Topic

how can I find all posts who belongs to category 'xyz' or to topic
'zrt' or forum 'uyi' ?

thanx in advance


You need to learn about associations by either reading Agile Web Development with Rails or searching the api at

You do this the same way. Determine WHAT you’re searching on and then write the finder.

Or use find_by_sql and do it the hard way

Or get really clever and use some advanced Ruby (see the constantize method on the string class in the Rails api.

Also, google for “beast” which is a ~500 or so line forum written in Rails by Rick Olson, a member of the Rails core (and a really swell guy!) You might find some answers there.

Associations are a basic thing and you need to get those down before you move ahead to anything bigger. The Agile book mentioned above is where you should start.

Good luck!

Also, I recommend a plugin called ‘ez_where’ which can be very nice for doing searches.