Topic: Best practice/fewest headaches for has_many/belongs_to

I'm writing a basic forum for a small community, and I'm wrestling on what's considered "best practice" in this situation.

Let's say I have topics and threads. (Or blogs and posts, etc.) Threads belong to topics, and they don't make sense outside the context of belonging to a topic. My question is, when displaying multiple "threads" it more correct to:

(1) create a controller method that displays all threads in a specific topic e.g.,

/topic/:id/threads

becomes
/topic/12/threads

(2) pass the topic ID to a thread method that displays all threads with that passed ID e.g.
/threads/:topicid

becomes
/threads/?topicid=12

I'm trying to create a situation where that context is respected, e.g., threads are always manipulated within the context of their topic, with a few exceptions.

#1 feels hacky, as I end up rendering a lot of partials from the thread views and trying to do much of the thread's work via the topic's controller - there's a lot of back and forth, but it works well. With this one I end up passing the topic ID to the thread controller for things like thread creation, via a hidden form element. #2 seems easier, but I'm not wild about passing the topic ID around.

Any thoughts are appreciated.

Last edited by synthemesc (2006-12-01 14:18:26)

Re: Best practice/fewest headaches for has_many/belongs_to

If you are using REST with Edge Rails, you may want to look into nested resources. In that case the URL would look like this:

/topics/1/threads

It would be mapped to the index action of the threads controller and assign the topic_id parameter appropriately.

To me, however, it makes more sense to just use the show action in the topics controller. I feel I have more control over the view since you are actually displaying the details of a Topic - along with the title and perhaps other information.

Looping through the children in the show action feels better to me than displaying the parent information in the index action of the children's controller.

BTW, Thread is a reserved word, so you may want to change the name of the model if that is the case.

Railscasts - Free Ruby on Rails Screencasts

Re: Best practice/fewest headaches for has_many/belongs_to

Thanks, ryanb, that explanation helps. Mostly I was just wondering if there was some inherently better way to do it that I wasn't considering.

Re: Best practice/fewest headaches for has_many/belongs_to

Strictly from a theoretical standpoint, I like

/topic/12/threads

It reads very naturally: "looking at topic 12's threads"

I have no idea what the various options mean code-wise though. So I'm not the help you are looking for. But even though it's a tiny, miniscule detail that most people don't notice at all, logical URLs are nice. That's actually one thing that drew me to RoR in the first place.