Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there a way to establish relationships only if included? #360

Closed
dahal opened this issue Dec 11, 2018 · 2 comments
Closed

Is there a way to establish relationships only if included? #360

dahal opened this issue Dec 11, 2018 · 2 comments

Comments

@dahal
Copy link

dahal commented Dec 11, 2018

For example:-

# Model
class Store < ApplicationRecord
  has_many :products
  has_many :customers
  has_many :orders
end

# Serializer
class StoreSerializer
  include FastJsonapi::ObjectSerializer
  attributes :id, :name

  has_many :products
  has_many :customers
  has_many :orders
end

# I have standard serializer (just like above) for all these models as well.
class Product < ApplicationRecord
  belongs_to :store
end

class Customer < ApplicationRecord
  has_many :orders
  belongs_to :store
end

class Order < ApplicationRecord
  belongs_to :store
  belongs_to :customer
end


customers = Customer.where(active: true).include(:orders)
ShopSerializer.new(customers)

☝️ makes N+1 database calls to Store table. What is the best way to avoid it?

@Mziserman
Copy link

Mziserman commented Dec 17, 2018

I use this :

# Serializer
def include_model?(params, model)
  params[:include].present? && params[:include].include?(model)
end
has_many :orders,
         if: proc { |_record, params| include_model?(params, :orders) }

# Controller
customers = Customer.where(active: true).include(:orders)
ShopSerializer.new(customers, {include: [:orders], params: {include: [:orders]}}) # first one for fja include logic, second for params in proc

@dpikt
Copy link

dpikt commented May 20, 2019

A solution to #357 should fix this use case.

@dahal dahal closed this as completed Dec 4, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants