我有一个包含3个主要表(用户,链接,主题)的数据模型,包含2个连接表(link_saves和link_topics)。我的模特:
用户
has_many :link_saves, :class_name => 'LinkSave', :foreign_key => 'user_id'
has_many :links, :through => :link_saves
LinkSave
belongs_to :user
belongs_to :link
链接
has_many :link_saves, :class_name => 'LinkSave', :foreign_key => 'link_id'
has_many :users, :through => :link_saves
has_many :link_topics, :inverse_of => :link
has_many :topics, :through => :link_topics
的LinkTopic
belongs_to :link
belongs_to :topic
主题
has_many :link_topics
has_many :links, :through => :link_topics
我希望能够找到用户保存链接的所有主题的列表。我希望能够做@user.topics
并让它从用户一直跳到主题的所有5个表。更重要的是,我希望这返回一个ActiveRecord关系,以便我可以进一步对用户主题列表进行范围/排序/分页,这样就不起作用了:
## app/models/user.rb
def topics
links.collect(&:topics)
end
我走错了路吗?有没有办法通过活动记录执行此操作而无需编写所有自定义SQL?求救!
has_many :through
来制作所有跃点。这有效,但不是最好的做法,对吗?## 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
答案 0 :(得分:0)
我认为这被称为'嵌套'has_many,基本上是从A到B再到C.
在Rails 3.1中,现在支持此功能 http://www.warmroom.com/yesterdays/2011/08/30/rails-3-1-nested-associations/
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html(搜索'嵌套')
他们的例子比你的例子简单,但我认为你应该有足够的想法。
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
在Rails 3.1之前有一个插件 'https://github.com/releod/nested_has_many_through'