我有这样的场景:最佳方式
class Category < ActiveRecord::Base
has_many :children, :class_name => "Category", :foreign_key => "parent_id"
belongs_to :parent, :class_name => "Category", :foreign_key => "parent_id"
def self.for_select
?? DO SOMETHING ??
end
end
而我只需要生成一个select_tag
这样的选择:
Category 1
- Subcategory 1
- Subcategory 2
- Subcategory 3
Category 2
- Subcategory 4
- Subcategory 5
我怎样才能做到这一点没有强调用循环查询的数据库?
其实,我有这样的事情,但它正在执行太多的疑问:
def self.for_select
ret = []
Category.where(parent_id: nil).each do |m|
ret << [m.name, m.id]
m.children.each { |c| ret << ["- #{c.name}", c.id] }
end
return ret
end
您可以加载孩子,以限制数据库调用次数。 'Category.where(parent_id:nil).includes(:children)' – Santhosh
@Santhosh是对的。我会将它作为“范围”添加... –