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:
Topic(id,name)
Post(id,content,topic_id)

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

thanx in advance

Pat

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=>[‘topics.name = ?’, “xyz”],

:include=>[:posts])

@post = @topic.posts

ok thanx,
and what if I have
Category(id,name)
Forum(id,category_id)
Topic(id,name,forum_id)
Post(id,content,topic_id)

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

Pat

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

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.