rails-api / active_model_serializers

ActiveModel::Serializer implementation and Rails hooks
MIT License
5.33k stars 1.39k forks source link

IdentityCache + ActiveModelSerializer #1508

Open mikeroher opened 8 years ago

mikeroher commented 8 years ago

Hey - I'm having some difficulties integrating Shopify's IdentityCache (v.0.3.1) gem with ActiveModelSerializers (v0.9.4).

Suppose, we have a Parent with a has_many Children association that is cached by IdentityCache. IdentityCache adds an extra method to the Parent model called fetch_children that would retreive the association from the cache.

My problem occurs when the Parent Serializer accesses the association, it uses the children method, not fetch_children. How would I go about writing an adapter(?) that would use the fetch_children method?

I've looked at #1317 but I'm not sure how that would solve this issue. I should note I am eagerloading the associations.

Many thanks,

Mike

bf4 commented 8 years ago

@mikeroher Thanks for writing. I can maybe help you debug if you provide some code examples. Also #1317 refers to 0.10.

mikeroher commented 8 years ago

@bf4 Thanks for the quick response.

Here's a code example:

# app/models/parent.rb
class Parent < ActiveRecord::Base
  has_many :children
  cache_has_many :children, inverse_name: :child
end

# app/models/child.rb
class Child < ActiveRecord::Base
  belongs_to :parent
  cache_belongs_to :parent
end

# app/serializers/parent_serializer.rb
class ParentSerializer < ApplicationSerializer
  attributes :id, :name, :age
  has_many :children
end

# app/controllers/parents_controller.rb
class ParentsController < ApplicationController
  def index
      @parents = Parent.includes(:children, ..... )
  end
end

My problem is that Parent.includes(:children) doesn't use the cached children. I could override the children method in the ParentSerializer but I am eagerloading throughout my app and this would result in a number of similar overridden methods across each serializer.

danielnc commented 5 years ago

bump!

Any updates?