我有這樣的場景:最佳方式
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是對的。我會將它作爲「範圍」添加... –