yosiat / panko_serializer

High Performance JSON Serialization for ActiveRecord & Ruby Objects
https://panko.dev
MIT License
592 stars 36 forks source link

Conditionally include associations in JSON response #141

Open kapso opened 1 year ago

kapso commented 1 year ago

Can I do something like this - ability to pass params or context to a serializer?

class UserSerializer < Panko::Serializer
  attributes :id, :name, :age

  # This will only include posts when if condition is true
  has_many :posts, if: -> { params[include_posts: true] }
end

UserSerializer.new(params: { include_posts: true })
yosiat commented 1 year ago

Hey,

You have two options to achieve this:

  1. Via Nested Filters
  2. In serializer with combination of passing "include_posts" as context and Filters For

If the name of the parameter you plan to pass is indicating which attributes/associations you want to serializer (like include_name / include_posts), then nested filters will fit you better. But, if your parameter is for example current logged in or other contextual information, which based on that you want to selectively serialize fields than context and filters for will be the best match here.

Does it makes sense?

kapso commented 1 year ago

@yosiat I can use filters, which will prevent that data from being returned. But I am also trying to prevent posts query to be made, maybe coz its expensive.

yosiat commented 1 year ago

@kapso when you use filters to filter out posts it shouldn't run the posts query (since posts won't be accessed)

Here is an example:

# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  # Activate the gem you are reporting the issue against.
  gem "activerecord", "~> 7.1.0"
  gem "sqlite3"
  gem "pg"

  gem "panko_serializer"
end

require "active_record"
require "logger"

# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'postgresql', database: 'rails_pg_guide')

ActiveRecord::Schema.define do
  create_table :posts, force: true do |t|
    t.integer :user_id
    t.text :context
  end

  create_table :users, force: true do |t|
    t.integer :age
  end
end

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
end

class PostSerializer < Panko::Serializer
  attributes :content
end

class UserSerializer < Panko::Serializer
  attributes :id, :name, :age
  has_many :posts, serializer: PostSerializer
end

# Create user with some data
user = User.create!(age: 18)
10.times { user.posts << Post.create!(user: user) }

# Use serializer
#  note: I am reloading the user, so it will re-issue the queries.
ActiveRecord::Base.logger = Logger.new(STDOUT)
pp UserSerializer.new(except: [:posts]).serialize(user.reload)

With this example, there is no query for posts. If I am missing something, please fix my example to show what you are seeing 🙏