Rails [tips] 利用 belongs_to 與 select 增進 db 效率

xdite · June 21, 2013 · Last by hooopo replied at June 21, 2013 · 2694 hits

原先的 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")

速度快了好幾秒以上...

好实用的 hack……

哦,不错的建议 现在数据一大,我就觉得 select 很有用了

3 Floor has deleted
You need to Sign in before reply, if you don't have an account, please Sign up first.