原先的 query 是這樣的
在 controller
@locations = @locations.includes(:state, :country, :auction_house).order("name ASC")
helper in view
def render_admin_auction_location_edit_link(location)
link_to(location.auction_house.try(:name), edit_admin_auction_house_location_path(location))
end
這段 code 本來普普通通是可以讓人接受的。但是因為資料庫數據驚人,而且 auction_house 本身欄位非常多。所以僅是 includes(:auction_house) 就有效率嚴重下降的問題...
所以我做了若干改進:
在 location.rb
裡面多造了一個
belongs_to :auction_house_only_name, :select => "auction_houses.name, auction_house.id", :class_name => "AuctionHouse"
def auction_house_name
auction_house_only_name.try(:name)
end
然後再把剛剛的 helper 改成
def render_admin_auction_location_edit_link(location)
link_to(location.auction_house_name, edit_admin_auction_house_location_path(location))
end
controller 改成
@locations = @locations.includes(:state, :country, :auction_houss_only_name).order("name ASC")
速度快了好幾秒以上...