Ruby on rails 如何返回嵌套资源的ActiveRecord关系
我有一门文章课Ruby on rails 如何返回嵌套资源的ActiveRecord关系,ruby-on-rails,ruby,activerecord,scope,thinking-sphinx,Ruby On Rails,Ruby,Activerecord,Scope,Thinking Sphinx,我有一门文章课 class Article < ActiveRecord::Base belongs_to :category end and Category class class Category < ActiveRecord::Base has_many :articles has_many :categories belongs_to :category end 所以,如果一个用户想要搜索政治,本地和世界都应该在桌面上,当他想要运动的时
class Article < ActiveRecord::Base
belongs_to :category
end
and Category class
class Category < ActiveRecord::Base
has_many :articles
has_many :categories
belongs_to :category
end
所以,如果一个用户想要搜索政治,本地和世界都应该在桌面上,当他想要运动的时候,我们会搜索足球,业余和职业拳击。
我的问题是,我如何编写一个方法/范围来返回所有类别在所选类别下的文章?请记住,我打算稍后使用ThinkingSphinx,因此它不可能是一个简单的数组,我需要ActiveRecord关系。您可以递归地将类别和子类别ID放入单个数组,然后在“where”子句中使用“IN”语句,如下所示:
class Category < ActiveRecord::Base
...
def all_subcategory_ids
cat_ids = []
cat_ids << self.id
self.categories.each do |category|
cat_ids << category.id
cat_ids << category.all_subcategory_ids
end
#since we have a mixed array of ids and sub-arrays, we need to flatten
#the cat_ids array so it is just a one-dimensional array of ids [Ruby Array#flatten](http://ruby-doc.org/core-2.0.0/Array.html#method-i-flatten)
cat_ids.flatten
end
end
类别 cat_id您可以递归地将类别和子类别id放入单个数组,然后在“where”子句中使用“IN”语句,如下所示:
class Category < ActiveRecord::Base
...
def all_subcategory_ids
cat_ids = []
cat_ids << self.id
self.categories.each do |category|
cat_ids << category.id
cat_ids << category.all_subcategory_ids
end
#since we have a mixed array of ids and sub-arrays, we need to flatten
#the cat_ids array so it is just a one-dimensional array of ids [Ruby Array#flatten](http://ruby-doc.org/core-2.0.0/Array.html#method-i-flatten)
cat_ids.flatten
end
end
类别class Article < ActiveRecord::Base
...
def self.in_category_and_subcategories(category)
Article.where("category_id IN (?)", category.all_subcategory_ids)
end
end