这些模型在Rails之间的适当关系是什么?

时间:2020-07-09 18:28:30

标签: ruby-on-rails join activerecord

我需要一些帮助来思考Rails应用程序中模型之间的适当关系。

在我的应用程序中,我希望用户能够根据主题关注其他用户的帖子。因此,例如,用户A可能希望关注用户B,但仅当用户B撰写有关主题X和Y(而不是主题Z)的文章时。主题就像应用程序中的标签,用户可以在其中为一个或多个主题添加标签。

这可能是这样的:

用户A在主题X和Y上紧随用户B

用户B在主题G和H上紧随用户A

用户C在主题D上关注用户A

用户C在主题P和Q上紧随用户B

我知道我需要用于用户,主题和帖子的模型,并且可能需要某种联接模型。但是我不确定联接表的结构以及在此处使用的适当的Active Record关系。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我建议使用一个名为users_topics的联接表

class User < ApplicationRecord
  has_many :users_topics, dependent: :destroy
  has_many :followed_user_topics, class_name: User, through: :users_topics
end

class UsersTopic < ApplicationRecord
  belongs_to :topic
  belongs_to :user
  belongs_to :followed_user, class_name: User, foreign_key: :followed_user_id
end

class Topic < ApplicationRecord
  has_many :users_topics, foreign_key: :followed_user_id
  has_many :following_users, :class_name User, through: :users_topics

  # there doesn't seem to be a reason to declare the other user association, 
  # which is also achieved through users_topics
end

所以,如果我们有:

     model     id
     User A    1
     User B    2
     Topic X   1
     Topic Y   2

然后users_topics表将包含:

     id        user_id     followed_user_id topic_id
     1            1            2               1
     2            1            2               2

因此,用户A具有用于用户B和主题X的UsersTopic实例,也具有用于用户B和主题Y的UsersTopic实例。

依次类推,针对您描述的其他每种情况