Justin Meltzer
Justin Meltzer

Reputation: 13548

What's the best Rails convention for this?

Let's say that you have a resource that is created and displayed entirely within the view of another resource (eg. comments or tags). Should you still make it it's own resource, or would it be a better idea to make it a nested resource? Also, should you make use of virtual attributes?

I know this question is general, but I'm not looking for a specific answer, just a general explanation of when each technique is preferred.

Upvotes: 1

Views: 118

Answers (2)

John F. Miller
John F. Miller

Reputation: 27217

Some general thoughts:

  • Nesting and independent resources are not necessarily mutually exclusive.
  • "created and displayed entirely within the view of another resource" is a strong statement that can end up not being true. For example, tags: do you ever want a list of all articles with a certain tag. that would not make sense nested.
  • Nesting below the second or third level will begin to be more trouble then its worth. Some will say that even the first nesting is more trouble then its worth.
  • For an app that has a single dominate resource the cost of adding other independent resources is proportionally higher. Small apps can get away with complexities that large apps cannot.
  • If you don't have a good feel yet write a few resources each way. Answers will at best be justifies opinions it is probably best to develop you own through experience.

Upvotes: 1

user689539
user689539

Reputation:

Generally speaking, it would be more useful to make it a nested resource. This is the more "RESTful" way. It will also give you access to the parent resource without having to specify it as a parameter. However, you do not want to nest a resource more than one level deep, as noted in the Rails routing guide.

Upvotes: 1

Related Questions