Rails中这些模型之间的正确关系是什么?
What is the proper relationship between these models in Rails?
我需要一些帮助来思考 Rails 应用程序中模型之间的适当关系。
在我的应用程序中,我希望用户能够根据主题关注其他用户 post。因此,例如,用户 A 可能想关注用户 B,但仅当用户 B 撰写有关主题 X 和 Y(而非主题 Z)的文章时。主题就像应用程序中的标签,用户可以在其中用一个或多个主题标记 post。
这可能是这样的:
用户 A 在主题 X 和 Y 上关注用户 B
用户 B 在主题 G 和 H 上关注用户 A
用户 C 在主题 D 上关注用户 A
用户 C 在主题 P 和 Q 上关注用户 B
我知道我需要用户、主题和 Post 的模型,并且可能需要某种连接模型。但我不确定连接表的结构和此处使用的适当 Active Record 关系。
感谢您的帮助!
我会建议以下内容,其中包含一个名为 users_topics
的连接 table
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 table 将包含:
id user_id followed_user_id topic_id
1 1 2 1
2 1 2 2
所以用户 A 有一个用户 B 和主题 X 的 UsersTopic 实例,还有一个用户 B 和主题 Y 的 UsersTopic 实例。
等等,对于您描述的每个其他场景
我需要一些帮助来思考 Rails 应用程序中模型之间的适当关系。
在我的应用程序中,我希望用户能够根据主题关注其他用户 post。因此,例如,用户 A 可能想关注用户 B,但仅当用户 B 撰写有关主题 X 和 Y(而非主题 Z)的文章时。主题就像应用程序中的标签,用户可以在其中用一个或多个主题标记 post。
这可能是这样的:
用户 A 在主题 X 和 Y 上关注用户 B
用户 B 在主题 G 和 H 上关注用户 A
用户 C 在主题 D 上关注用户 A
用户 C 在主题 P 和 Q 上关注用户 B
我知道我需要用户、主题和 Post 的模型,并且可能需要某种连接模型。但我不确定连接表的结构和此处使用的适当 Active Record 关系。
感谢您的帮助!
我会建议以下内容,其中包含一个名为 users_topics
的连接 tableclass 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 table 将包含:
id user_id followed_user_id topic_id
1 1 2 1
2 1 2 2
所以用户 A 有一个用户 B 和主题 X 的 UsersTopic 实例,还有一个用户 B 和主题 Y 的 UsersTopic 实例。
等等,对于您描述的每个其他场景