I have a post controller that has many comments.
The post model has a field called has_comments which is a boolean (so I can quickly select from the database only posts that have comments).
To create a new comment for a post, I use the create action of my comments controller.
After I create the comment I need to update my post’s has_comments field and set it to true.
I can update this field from the create action of my comments controller, but that doesn’t seem right – I feel that I should really be using the post’s update action, but I’m not sure if it’s right to call it (via send?) from the create action of the comments controller.
Where should the code for updating the post be?
Thank you!
Why clutter your database with another column when the interface is programmatic? Make has_comments a method on Post:
Then implement a counter_cache as suggested to reduce the query load.
EDIT: Alternatively, after implementing a counter cache, you could use a named_scope on Post to retrieve all posts that have comments, using a single query, if that’s the main goal:
EDIT: You can also avoid the famous n+1 query problem by a judicious use of :include: