这可以通过关联重写为has_many吗?



我正在做一些轨道关联练习,我有以下关联

class User
   has_many :videos
end
class Video
   has_many :comments
   belongs_to :user
end
class Comment
  belongs_to :user
  belongs_to :video
end

上面的方式对我来说是有意义的。我想得到以下内容:

user1 = User.find(1)
user1.videos  #A user's associated videos
user1.comments #A user's associated comments
user1.videos.first.includes(:comments) #A particular user video's comments

这对我来说似乎是可以接受的,但有些事情告诉我这可能会更好。是否存在潜在的has_many :through关联,如"用户通过视频有很多评论?我认为这不是一个正确的关联,因为评论不能通过视频吸引很多用户。我可以使用"has_many:通过"那只去一个方向吗?

首先,你缺少User.has_many :comments

class User
   has_many :videos
   has_many :comments
end
class Video
   has_many :comments
   belongs_to :user
end
class Comment
  belongs_to :user
  belongs_to :video
end

如果您想查找特定用户对特定视频的评论...

user.comments.where( video: video )

反之亦然。

video.comments.where( user: user )

请注意,User.has_many :videos有点奇怪。用户除了评论视频之外,还拥有视频吗?我认为您可能打算user.videos用户评论的视频。在这种情况下...

class User
  has_many :comments
  has_many :commented_videos, through: :comments, class_name: "Video"
end

现在,您可以获取用户评论的视频。

videos = user.commented_videos

请注意,我避免将这种关联称为简单:videos以明确这些是用户评论的视频,而不是用户的视频。

class User
   has_many :videos
   has_many :comments, through: :videos
end
class Video
   has_many :comments
   belongs_to :user
end
class Comment
  belongs_to :video
end

如果它满足预期行为,请尝试上述关联。

相关内容

最新更新