Skip to content

Instantly share code, notes, and snippets.

@dascgo
Last active September 9, 2015 12:45
Show Gist options
  • Save dascgo/c61b7df1f7c9cd48ae41 to your computer and use it in GitHub Desktop.
Save dascgo/c61b7df1f7c9cd48ae41 to your computer and use it in GitHub Desktop.
No memoization between associations?
class Group
has_many :things
# external data would look like:
# {
# things: {
# 1: "some data for 1",
# 2: "some data for 2",
# etc...
# }
# }
def external_data
@external_data ||= begin
puts "making api call to get external data"
results = SOME_API_CALL.body
end
end
end
class Thing
belongs_to :group
def data
@data ||= group.external_data.things[id]
end
end
# Invoke:
> @group = Group.find(1)
> @group.things.each { |thing| puts "#{thing.id} = #{thing.data}" }
# Expected Results:
=> making api call to get external data
=> 1 = some data for 1
=> 2 = some data for 2
etc.
# Actual Results, API call is made for every has_many assoc:
=> making api call to get external data
=> 1 = some data for 1
=> making api call to get external data
=> 2 = some data for 2
etc.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment