In this episode, we set up the foundation for displaying messages in our app! We start by creating a Message Index Controller, which is responsible for giving us a list of messages for a particular room. First, we define a new route and hook it up to this controller, making sure our endpoint is protected and only accessible to authenticated users.
Next, we tweak our Room model to include a relationship—this way, we can easily fetch all the messages that belong to a given room. Then, it’s time to build a Message Resource, so we can control exactly what data gets sent back for each message. To keep things simple at first, we only return the message ID and body. Later, we expand this to include the user who posted each message.
Speaking of users, we create a relationship on the Message model back to the User, and then set up a dedicated Public User Resource to handle user info in our API response. We make sure to eagerly load the user relationship so our app stays speedy and doesn't run into unnecessary database queries (avoiding the dreaded N+1 problem!).
We cap things off by adding an avatar to each user. This is a fun little touch using UI Avatars, so users have a visual representation next to their messages. By the end, we’ve got a fully functional messages endpoint that returns everything we need: message body, user info, avatar, and more — all optimized for performance and ready for the front end to render.
If you follow along, you'll now have a solid endpoint for fetching paginated, nicely-formatted messages in any room of your app!