HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrubyrailsMinor

Find associated object if exists, otherwise generate it

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
findgenerateassociatedexistsobjectotherwise

Problem

I have a simplified model that looks like this:

class Player  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?

Solution

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!.

Code Snippets

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

Context

StackExchange Code Review Q#1558, answer score: 7

Revisions (0)

No revisions yet.