【问题标题】:Rails belongs_to many models [closed]Rails 属于许多模型[关闭]
【发布时间】:2010-10-12 05:22:55
【问题描述】:

我确实在 SO 上发现了一些关于 Rails 关联的问题,这些问题有点像我的问题,但在我的一生中,我似乎无法理解如何使用 belongs_to 多个模型。

这是我想要的表结构

User
 id

Post
 id
 user_id #foreign key; a post belongs to a User aka "Who created this post"

Comment
 id
 user_id #foreign key; a comment belongs to a User aka "Who made this comment"
 post_id #foreign key; a comment belongs to a Post aka "What post this comment is for"

还有联想

User
 has_many :posts
 has_many :comments

Post
 belongs_to :user
 has_many :comments

Comment
 belongs_to :user
 belongs_to :post

这是正确的方法吗?

【问题讨论】:

  • 如何继续保存 cmets?
  • 天啊,我学习 Rails 已经 7 年了(谢谢!)。要回答您的问题@MosesNdeda,您将实例化一个评论,分配用户和帖子对象,然后在评论对象上调用save

标签: ruby-on-rails activerecord belongs-to


【解决方案1】:

是的,这是正确的方法。

【讨论】:

  • 这是否需要连接表或其他任何东西...
  • 这些是一对多的关系(一个用户有很多帖子等),因此不是。 cmets 表应如下所示:id user_id post_id 和 ofc content 或其他。
  • 你能输入 has_many :posts, :cmets
  • 问题:在第一篇文章中你会这样做:current_user.post.build(params[:post]) 但是在评论中你如何在评论中同时赋予用户 ID 和帖子 ID带有帖子 ID 的隐藏字段?
  • 这个问题及其答案解释了如何很好地做到这一点:stackoverflow.com/questions/11539151/…
【解决方案2】:

虽然并不总是“最佳”方法,Rails 提供了所谓的Polymorphic belongs_to association。它会阻止您在数据库中定义外键,因为 xxx_id 列引用了许多可能表之一中的 id,而另一列指定了该表模型的名称,但它使关系在 Rails 中更加明确。此外,它将模型限制为仅属于其他模型之一,而不是属于一个或多个模型,因为它会在使用多个外键的设置时发生,而无需一些额外的数据库魔法。

【讨论】:

    猜你喜欢
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    相关资源
    最近更新 更多