Find associated object if exists, otherwise generate it I have a simplified model that looks like this:

class Player &lt; ActiveRecord::Base
  has_many :picks

  def pick_for_game(game)
    id = game.instance_of?(Game) ? game.id : game
    pick = picks.find {|pick| pick.game_id == id}
    if !pick
      pick = picks.build(:game_id =&gt; id)
    end
    pick
  end
end


The pick_for_game method usually is called a bunch of times when an action is executed. What would be a good way to make this code work efficiently with a list of games?
You can use find_or_initialize_by dynamic finder, see a guide here

This would be equivalent to your code:

def pick_for_game(game)
  game_id = game.instance_of?(Game) ? game.id : game
  picks.find_or_initialize_by_game_id(game_id)
end


Hope it helps you!.