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!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With