【问题标题】:Can this be rewritten as a has_many through association?这可以通过关联重写为 has_many 吗?
【发布时间】:2019-07-12 23:08:42
【问题描述】:

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

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 关联,如“一个用户通过视频拥有许多 cmets?”我认为这不是一个正确的关联,因为评论不能通过视频拥有很多用户。我可以使用“has_many :through”吗?那只能是一个方向?

【问题讨论】:

  • 用户拥有视频是您的意图吗?

标签: ruby-on-rails


【解决方案1】:

首先,您缺少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

如果您想在特定视频上查找特定用户的 cmets...

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,以明确这些是用户评论过的视频,而不是用户的视频。

【讨论】:

    【解决方案2】:
    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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多