Rails3通过问题嵌套has_many
我们计划将我们的应用程序升级到 Rails3。我们经常使用的一个插件是nested_has_many_through。这个插件似乎已经过时,不再维护,并且似乎无法在新的 Rails3 应用程序中工作。
一个简单的例子:
Author.rb
has_many :posts
has_many :categories, :through => :posts, :uniq => true
has_many :related_posts, :through => :categories
Post.rb
belongs_to :author
belongs_to :category
Category.rb
has_many :posts
任何人都可以推荐处理这个问题的最佳实践方法,或者一个有效的 Rails3 插件吗?
谢谢!!
We are planning to upgrade our application to Rails3. One plugin we've used quite a bit is nested_has_many_through. This plugin seems outdated, and no longer maintained, and simply does not appear to be working in a new Rails3 application.
A simple example:
Author.rb
has_many :posts
has_many :categories, :through => :posts, :uniq => true
has_many :related_posts, :through => :categories
Post.rb
belongs_to :author
belongs_to :category
Category.rb
has_many :posts
Can anyone recommend the best practice way to handle this, or a working Rails3 plugin?
Thanks!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是内置于 Rails 3.1 中的: http://asciicasts.com/episodes/265 -rails-3-1-概述
This is built in with Rails 3.1: http://asciicasts.com/episodes/265-rails-3-1-overview
我对 has_many :lated_posts 部分感到更困惑。您是否想将分类帖子本质上合并在一起?例如,“x”类别中的所有帖子都被视为“相关”?如果是这样,那么由于没有相关帖子类,这将不起作用,因此要至少解决此问题,您必须在关联上指定 :class_name :
但其次,这可能不是正确的方法。由于任何作者都已经通过author_id外键发布了has_many帖子,因此尝试回溯类别表是没有意义的,而是使用分组逻辑。
清理这个问题的替代方法:
Author.rb
当然,如果这不是您想要实现的目标,那么所有这些都是没有意义的。 :P
I'm more confused by the has_many :related_posts part. Are you trying to essentially join together categorized posts? Like, all posts in 'x' category are considered 'related'? If so, this won't work based on there not being a RelatedPost class, so to fix this at a bare minimum, you'd have to specify :class_name on the association:
But secondly, it's probably not the correct approach to begin with. Since any author already has_many posts via the author_id foreign key, there is no sense in trying to weave back through the categories table, instead use grouping logic.
Alternate approaches that clean this up:
Author.rb
Of course, all of this is moot if it wasn't what you were trying to accomplish. :P
Rails 3(未经测试,首先按最相关类别的帖子排序):
category.rb:
用法:
Rails 3 (untested, orders by posts with most related categories first):
category.rb:
Usage: