-
Notifications
You must be signed in to change notification settings - Fork 35
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
Conditionally include associations in JSON response #141
Comments
Hey, You have two options to achieve this:
If the name of the parameter you plan to pass is indicating which attributes/associations you want to serializer (like Does it makes sense? |
@yosiat I can use filters, which will prevent that data from being returned. But I am also trying to prevent |
@kapso when you use filters to filter out 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. |
Can I do something like this - ability to pass params or context to a serializer?
The text was updated successfully, but these errors were encountered: