Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested resource with multiple parent resources in Rails 3

I want to create a model to store comments related to articles. I have a strong feeling that in the future I will want comments on other objects in the app too. How do I design commenting in my app so that it will be forward compatible with adding new parent objects. I want to avoid a scenario where have multiple controllers/models for each object to comment relationship.

After watching Ryan Bates screen cast on Nested Resource I have a firm grasp on how tp nest a resource under a single parent. How do I achieve this under 2 or more parent resources?

Thanks!

like image 374
Tim Santeford Avatar asked Dec 13 '10 22:12

Tim Santeford


People also ask

What is Nested routing in Rails?

Rails Nested Resources Nested resources in rails give us the ability to document parent/child relationships directly in our routes. Here we have the parent (Coffee) and the child(Review) taken from the two models User and Review. Nested routes are another way of capturing these relationships through your routing.

What is the difference between resource and resources?

Singular routes* are a little different – they are written as singular resource . Declaring a resource or resources generally corresponds to generating many default routes. resource is singular. resources is plural.

What nested resources?

Nesting resources provide REST API consumers an easy and efficient way to manage data by allowing the consumer to send and receive only the required object. The nested resource must be a business object, that is, it must still represent a complete business object.


1 Answers

For "forward compatible with adding new parent objects" part of the question:

You could use Polymorphic Associations. Here's a nice example. Also see RailsCast #154.

An example of how it could look like for you:

The comments table columns' could be like this:

id:integer
commentable_type:string
commentable_id:integer
comment_text:string

Some Sample records:

1,'Article',12,'My first comment' #comment on an Article model
2,'Question',12,'My first comment' #comment on a Question model
3,'Question',15,'My first comment' #comment on a Question model
like image 60
Zabba Avatar answered Sep 29 '22 22:09

Zabba