ruby on rails - Not sure how to optimize active record association -
i have piece of code gets associated object id, otherwise initializes new object.
def pick_for_game(game_id) picks.find_or_initialize_by_game_id(game_id) end the picks collection typically have several hundred items in it. 2 use cases are:
i want call method 15-30 games
i want call method games
seems current approach ok use case a, absolutely terrible use case b. make method complicated based on whether or not picks has been eagerly loaded following:
def pick_for_game(game_id) if picks.loaded? new_pick = proc { pick.new |p| p.game_id = game_id end } picks.detect(new_pick) |p| p.game_id == game_id end else picks.find_or_initialize_by_game_id(game_id) end end however, picking 1 approach on other cases have merit other making code little cleaner? other solutions problem?
assuming pick model, if know list of game_ids can fetch existing picks specified games in 1 query , initialize new picks remaining game_ids:
def picks_for_games( game_ids ) existing_picks = pick.all( :conditions => { :game_id => game_ids } ) game_ids_without_picks = game_ids - existing_picks.map{ |x| x.game_id } new_picks = game_ids_without_picks.map { |game_id| pick.initialize_by_game_id( game_id ) } return picks + new_picks end you switch between 2 implementations depending on:
if game_ids.is_a?( array ) an option b) add association on game picks reference can query games have no pick(s) , initialize pick each.
game.all( :conditions => { :picks => nil } ).map { |game| pick.initialize_by_game_id( game.id ) }
Comments
Post a Comment