【问题标题】:ActiveRecord associations between 2 models that belong to the same model属于同一模型的 2 个模型之间的 ActiveRecord 关联
【发布时间】:2016-08-18 23:24:13
【问题描述】:

Rails 新手,请耐心等待。我需要有关如何在我的两个模型之间正确设置活动记录关联的建议。

就目前而言,我有一个用户模型。一个用户有_许多联系人。和一个用户 has_many Posts。简单地说:

class User < ApplicationRecord
  has_many :posts, dependent: :destroy
  has_many :contacts, dependent: :destroy

class Contact < ApplicationRecord
  belongs_to :user

class Post < ApplicationRecord
  belongs_to :user

用户可以将帖子发送给他们的一个或多个联系人(虽然该操作只是触发电子邮件的操作,但我需要能够跟踪并显示他们将每个帖子发送给了哪些联系人)。他们可以向多个联系人发送帖子,并且他们可能(随着时间的推移)向每个联系人发送超过 1 个帖子。

我有点不确定如何关联帖子和联系人。它只是一个简单的 Post has_many Contacts(反之亦然)吗?或者应该是一个帖子通过一个用户有很多联系人?

虽然我通常是通过反复试验来学习的人,但这是我担心如果我在这里走错路的情况之一,我会很晚才弄清楚它会撤消会很痛苦 - 所以感谢您的任何建议。

我使用 Rails 5 是为了物有所值。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    您正在寻找的是多对多关系。因为一个帖子可以关联很多联系人,而一个联系人可以关联很多帖子。

    这是many-to-many relationship 的精彩读物

    基本上,您将被创建一个关联表来帮助链接帖子和联系人表。

    class Contact < ApplicationRecord
      belongs_to :user
      has_many :posts, through: post_contact
    
    class Post < ApplicationRecord
      belongs_to :user
      has_many :contacts, throught: post_contact
    

    您将创建一个名为 post_contact(或任何您想要的)的新连接表,该表提供帖子和联系人之间的关联。

    希望这会有所帮助。

    【讨论】:

    • 谢谢!这听起来像是我正在做的事情的正确方法。
    【解决方案2】:

    您不一定需要 PostContacts 之间的连接,即您可以编写 @post.user.contacts@contact.user.posts,尽管这取决于您的用例。

    但是假设您确实想为Post 创建一个关联以获取同一用户的所有 cmets。你可以写:

    class Post < ActiveRecord::Base
      has_many :contacts_of_user, through: :user, source: :contacts
    end
    

    您也可以使用相同的逻辑来实现contact.posts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多