【问题标题】:Creating collections of posts with Rails 5 (as in Pinterest Boards)使用 Rails 5 创建帖子集合(如在 Pinterest Boards 中)
【发布时间】:2018-08-06 12:12:03
【问题描述】:

我有 500 多个帖子,并且增长迅速。我想为用户提供一个功能来创建集合 [标题、描述、帖子] 并将帖子分配给他们。 1 个帖子可以属于来自不同用户的多个集合。

示例:

  • 用户 A 创建了一个名为“DARK DESIGNS”的集合
  • 用户 A 在发布/展示页面点击“添加到收藏”按钮并选择她自己的“深色设计”收藏
  • 用户 A 进入另一个帖子并将更多帖子分配到“黑暗设计”中
  • 用户 A 在她的个人资料中看到她的收藏列表

问题:

我应该如何构建这个集合功能?我应该只做脚手架集合吗?我应该如何在数据库中保存帖子 ID,只是在用逗号分隔的字段中?

谢谢


我需要用户能够创建集合并将 1 个帖子分配给多个集合。

我的数据库结构应该是这样的:

现有表

表格[帖子]

  • 身份证
  • 标题
  • 图片
  • 更多字段

表[用户]

  • 身份证
  • 用户名
  • 更多字段

新表

表[集合]

  • 身份证
  • 标题
  • 描述
  • user_id

表 [collections_posts]

  • 身份证
  • post_id
  • collection_id

【问题讨论】:

    标签: ruby-on-rails collections ruby-on-rails-5 grouping bucket


    【解决方案1】:

    我认为您需要一个带有 titledescription 字段的单独 Collection 模型,以及用于 has_many 关联的额外 CollectionsPost 模型。

    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
    

    如果您想在个人资料页面上显示用户集合列表,那么集合可能应该属于用户。

    【讨论】:

    • 啊好的,所以我不应该在集合中包含任何 user_id 或在帖子表中包含 collection_id。相反,我应该有一个单独的 CollectionsPosts 表,其中包含 collection_id 和 post_id 字段。所以我可能需要为 CollectionsUsers 多一张单独的表。 ?
    • 或者实际上我想我可以将 user_id (Devise) 添加到 Collections 表中,对吧?毕竟,每个集合都属于一个用户。
    • @Designer,我看到了您的问题更新,但我无法在问题下方发表评论(声誉不足)。是的,您对模型结构的看法是正确的
    • 感谢您的指导,我找到了一些关于 has_many :through 的详细教程,可以满足我的需要
    • @Designer,一点也不:)
    猜你喜欢
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2021-10-02
    • 2012-06-17
    • 2012-05-14
    • 2020-09-17
    相关资源
    最近更新 更多