geoboy
geoboy

Reputation: 1262

Conditional except, only, include in render json for Rails

Can one have conditional except, only or include options when rendering? So, like in the example below:

render json: @post,
except: [:author]

Is it possible to have that except option or a similar option be conditional?

Ideally, something along the lines of a conditional way of doing this that allows me to deal with many different conditions and cases.

Like maybe something like:

render json: @post,
except: return_excluded_keys

return_excluded_keys function could return keys that need to be excluded.

I am using Rails 4.2.6 and Active Model Serializers 0.9.3.

Upvotes: 1

Views: 4475

Answers (2)

Canh
Canh

Reputation: 739

Maybe:

render json: @post.as_json(except: [:author])

Upvotes: 5

Joe Woodward
Joe Woodward

Reputation: 453

Conditional attributes in Active Model Serializers

https://github.com/rails-api/active_model_serializers/issues/825

I believe these should point you in the right direction. You can pass a condition to the serialiser and then manually construct the output.

Upvotes: 0

Related Questions