Question

I am trying to get better with Rails and nesting resources. A User has many Event (and vice versa) through UserEvent join table. I also want a User to Comment on an Event. So far, Event is nested under User in my resources. How would you nest Comment? Would that be nested under Event so there are two successively nested resources under User? How would that work?

Was it helpful?

Solution

I think this would be my suggested nested approach:

resources :users
resources :events do
  resources :comments
end

In a many-to-many relationship, it doesn't usually make sense to nest one under the other because neither has a stronger containment relationship.

In your scenario, a user doesn't belong to one event and an event doesn't belong to one user, so having your routes represent it like that doesn't quite model the relationship. Your URLs would look like /events/1/users/2. That sort of implies that User 2 only exists in Event 1.

I think it would make sense that your User and Event are top-level resources. Comments, on the other hand, do have some ownership which makes sense to nest. More than likely, a Comment will be associated with the Event in regards to context. The User is simply the person responsible for it. Nesting comments under the user would give you easy URLs to display all the comments for a user, but I'm betting you're more likely to display all the comments for an Event. With that in mind, I would suggest nesting Comments under Events.

This also makes sense if you were to delete the user and nullify the user_id in the Comment model. You could still have a URL for the comment. If you delete the Event, the comments likely aren't useful anymore anyway, so you could simply destroy them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top