Skip to main content

How to display multiple models in the same infinite scroll

General • Asked by Aaron Mills

So I have a Post model and a Category model and a User model.

So a user can have many posts and a post can have many categories. So returning a group of posts is very easy, however a post can have a variety of different content.

One post might be a blog post, while another might be a video, while another might be a poll.

Im tryin to figure out the best way to structure the data so that I can return a mixed list of post types, ranked by their number of likes, as fast as possible, with as few database calls as possible, while feeding those posts into an infinite scroll.

Should I just create a post_type field in my post model or would I be better off letting posts have child models for the different kinds of content?


Hey Aaron!

It might make the most sense to have a post_type field that's video, blog, or poll. You could then dynamically add new types easily and have each of these render out different partials based upon the type. That's really the simplest way of doing it. You'll still query one model which keeps things all together, but the rendering will show the different types of content.

You can also take this a step further with what's called Single Table Inheritance or STI. You could create Blog, Video, and Poll models that inherit from Post and then you can organize your code out nicely inside these various models for the code that's specific to each type.

More reading for you on STI: http://eewang.github.io/blog/2013/03/12/how-and-when-to-use-single-table-inheritance-in-rails/


Thanks Chris that is exactly the input I was looking for!


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.