有没有办法根据parent_id关联模型,然后与另一个模型关联?

时间:2012-08-03 02:54:44

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

这个标题听起来很奇怪,所以让我试着解释一下我想要完成什么。

假设我有一个Category模型,结构看起来有点像这样:

类别

ID

名称

PARENT_ID


我也有文章的模型

制品

ID CATEGORY_ID


如果我有一个名为“News”且id为1的类别,然后是一个名为“World News”的子类别,其id为:2,parent_id:1,如果我有一篇包含category_id:1的文章和另一篇文章使用category_id:2,我希望能够做到这样的事情:

category = Category.find 2 # This is the subcategory
category.articles # => Shows just the article belonging to that category

category = Category.find 1 # This is the parent category
category.articles # => Shows BOTH articles, the one for the child and the one for parent

这有意义吗?

1 个答案:

答案 0 :(得分:1)

您正在寻找的是您的类别的树结构。使用parent_id是实现它的最明显的方法,但是当你想查询孩子时它会变得复杂。

更好的解决方案是使用nested set,这会在插入/删除时添加一些复杂功能,但会通过非常简单的查询获得回报。

你可以做研究来实现这个,但是和rails中的很多东西一样,这是一个已经解决的问题。使用awesome_nested_set将为您完成所有这些工作。

安装gem后,创建此迁移:

def up
  add_column :categories, :lft, :integer
  add_column :categories, :rgt, :integer

  Category.reset_column_information!
  Category.rebuild!
end

def down
  remove_column :categories, :lft
  remove_column :categories, :rgt
end

然后将此行添加到您的模型中:

class Category < ActiveRecord::Base
  acts_as_nested_set

  # ...
end

您可以使用这样的查询来获取所有文章:

category = Category.find(1) # Or any category id

category.self_and_descendants.articles
相关问题