Search code examples
ruby-on-railscollectionsruby-on-rails-5groupingbucket

Creating collections of posts with Rails 5 (as in Pinterest Boards)


I have over 500 posts and growing rapidly. I want to give a feature for users to create collections [title, description, posts] and assign posts to them. 1 post can belong to many collections from different users.

Example:

  • User A creates a collection named "DARK DESIGNS"
  • User A clicks "add to collection" button in post/show page and selects her own "Dark Design" collection
  • User A goes into another post and assigns more posts into "Dark Design"
  • User A sees list of her collections at her profile

Question:

How should I structure this collections feature? Should I just do scaffold collections? How should I hold post ids in database, just in a field separated with commas?

Thank you


I need users to be able to create collections and assign 1 post to multiple collections.

Should my database structure be like:

Existing tables

table [posts]

  • id
  • title
  • image
  • many more fields

table [users]

  • id
  • username
  • many more fields

New tables

table [collections]

  • id
  • title
  • desc
  • user_id

table [collections_posts]

  • id
  • post_id
  • collection_id

Solution

  • I think that you need a separate Collection model with title and description fields, and additional CollectionsPost model for has_many association.

    class CollectionsPost < ApplicationRecord
      belongs_to :collection
      belongs_to :post
    end
    class Collection < ApplicationRecord
      has_many :collections_posts
      has_many :posts, through: :collections_posts
    end
    class Post < ApplicationRecord
      has_many :collections_posts
      has_many :collections, through: :collections_posts
    end
    

    And maybe Collection should belong to User, if you want to display list of users collections on the profile page.