snippetrubyrailsMinor
Find associated object if exists, otherwise generate it
Viewed 0 times
findgenerateassociatedexistsobjectotherwise
Problem
I have a simplified model that looks like this:
The
class Player id)
end
pick
end
endThe
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
This would be equivalent to your code:
Hope it helps you!.
find_or_initialize_by dynamic finder, see a guide hereThis 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)
endHope 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)
endContext
StackExchange Code Review Q#1558, answer score: 7
Revisions (0)
No revisions yet.