Activerecord 活动记录关系联接-3个主表,2个联接表 设置

Activerecord 活动记录关系联接-3个主表,2个联接表 设置,activerecord,ruby-on-rails-3.1,data-modeling,scoping,Activerecord,Ruby On Rails 3.1,Data Modeling,Scoping,我有一个数据模型,有3个主要的表用户、链接、主题和2个连接表链接保存和链接主题。我的模型: 使用者 链接保存 belongs_to :user belongs_to :link 链接 链接主题 belongs_to :link belongs_to :topic 话题 问题 我希望能够找到一个用户已保存链接的所有主题的列表。我希望能够做到@user.topics,并让它在所有5个表中从user跳到topics。更重要的是,我希望它返回一个ActiveRecord关系,这样我就可以进一步对用户

我有一个数据模型,有3个主要的表用户、链接、主题和2个连接表链接保存和链接主题。我的模型:

使用者

链接保存

belongs_to :user
belongs_to :link
链接

链接主题

belongs_to :link
belongs_to :topic
话题

问题 我希望能够找到一个用户已保存链接的所有主题的列表。我希望能够做到@user.topics,并让它在所有5个表中从user跳到topics。更重要的是,我希望它返回一个ActiveRecord关系,这样我就可以进一步对用户主题列表进行范围/排序/分页,这样就不起作用了:

## app/models/user.rb

def topics
  links.collect(&:topics)
end
我走错路了吗?有没有一种方法可以通过活动记录做到这一点,而不必编写所有自定义SQL?救命啊

可能的答案更新 使用multiple has_many:through进行所有跳跃。这是可行的,但不是最好的做法,对吗?
我认为这就是所谓的“嵌套式”,基本上是从a到B再到C

在Rails 3.1中,现在支持此功能

搜索“嵌套”

他们举的例子比你举的要简单一些,但我认为这应该足以让你得到一些想法

class Author < ActiveRecord::Base
  has_many :posts
  has_many :comments, :through => :posts
  has_many :commenters, :through => :comments
end

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :commenter
end

@author = Author.first
@author.commenters # => People who commented on posts written by the author
在Rails3.1之前,有一个插件
'https://github.com/releod/nested_has_many_through

我认为这被称为“嵌套式”结构,基本上从a到B再到C

在Rails 3.1中,现在支持此功能

搜索“嵌套”

他们举的例子比你举的要简单一些,但我认为这应该足以让你得到一些想法

class Author < ActiveRecord::Base
  has_many :posts
  has_many :comments, :through => :posts
  has_many :commenters, :through => :comments
end

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :commenter
end

@author = Author.first
@author.commenters # => People who commented on posts written by the author
在Rails3.1之前,有一个插件
'https://github.com/releod/nested_has_many_through“

这确实起到了作用,我把在我的特定案例中起作用的最终解决方案放在上面。我会投票,但斯塔克认为我的名声还不够好!你不能投票给自己的问题一个答案,这太疯狂了。希望其他人会这样做。这确实起到了作用,我把在我的特定案例中起作用的最终解决方案放在上面。我会投票,但斯塔克认为我的名声还不够好!你不能投票给自己的问题一个答案,这太疯狂了。希望其他人会。
## app/models/user.rb

def topics
  links.collect(&:topics)
end
## app/models/user.rb
has_many :link_saves, :class_name => 'LinkSave', :foreign_key => 'user_id'
has_many :links, :through => :link_saves
has_many :link_topics, :through => :links, :uniq => true
has_many :topics, :through => :link_topics, :uniq => true
class Author < ActiveRecord::Base
  has_many :posts
  has_many :comments, :through => :posts
  has_many :commenters, :through => :comments
end

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :commenter
end

@author = Author.first
@author.commenters # => People who commented on posts written by the author