【问题标题】:how to set up this association and model migration?如何建立这个关联和模型迁移?
【发布时间】:2013-01-30 14:26:43
【问题描述】:

我有用户、帖子和 cmets。帖子属于用户。用户有很多帖子。

现在我感到困惑的是,用户应该能够评论其他人的帖子。 如何建立此关联?

是不是应该写users有很多cmets,posts有很多cmets,cmets属于posts和users?或者用户通过帖子有很多 cmets? 模型表还应该有哪些列?需要user_id、post_id、content吗?

【问题讨论】:

    标签: ruby-on-rails-3 migration associations


    【解决方案1】:

    使用has_many :through Association

    用户模型:

    has_many :posts
    has_many :comments, :through => :posts
    

    后模型:

    belongs_to :user
    has_many :comments
    

    评论模型:

    belongs_to :post
    belongs_to :user
    

    【讨论】:

    • 到底使用 :through 会做什么?在这种情况下,我不需要 user_id 列?
    • 要查找哪个用户评论了哪个帖子,您需要 cmets 表中的 user_id 和 post_id 列。
    【解决方案2】:

    你第一次是对的。

    用户有很多 cmets。帖子有很多cmets。评论属于用户。评论属于帖子。

    cmets 表应该有 user_id 和 post_id。

    所以user.comments 将是用户创建的cmets。 post.comments 将成为该帖子的 cmets。

    这是一个关联,表示“此用户评论了此帖子。”

    【讨论】:

      猜你喜欢
      • 2013-10-24
      • 2021-07-06
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      相关资源
      最近更新 更多