user5710450
user5710450

Reputation:

How to avoid querying multiple times in serializer?

I have a model story.rb with field product_ids. it is a Arrayof ids. in story_controller show action I have to return a story with it's products and stores. I am returning response through story_serializer. like this

Note: story has no association with store

class StorySerializer < ActiveModel::Serializer
  ----
  ----
 def products
    here my query for products using `product_ids`
 end

 def stores
    here is the problem
    to find stores, I have to find product's first and then find store's of that product. so again I am querying for products here.
 end

end

I have product_ids so i can easily returns all the related products of that story, but the problem is to return related stores. How can I return store's without querying for products again. Any suggestions would be helpful.

Upvotes: 0

Views: 450

Answers (1)

Pascal
Pascal

Reputation: 8646

You can use memoization:

def products
  @products ||= begin
    some code 
    more code
   end
end

or if it is just a short piece of code

def products
  @products ||= some code
end

Upvotes: 1

Related Questions