1

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.

geoboy
  • 1,172
  • 1
  • 11
  • 25

2 Answers2

5

Maybe:

render json: @post.as_json(except: [:author])
Canh
  • 709
  • 1
  • 6
  • 24
  • Sorry, I might not be following. How does this allow the `except` part to be conditional? – geoboy Aug 02 '16 at 03:13
  • Oops, I'm very sorry I misunderstood your question. Do you mean rendering `author` only some condition meets? If so, why don't just use ternary operator `condition ? render(json: @post) : render(json: @post, except: [:author])` – Canh Aug 02 '16 at 03:25
  • I was hoping for some conditional way of doing this that allows me to deal with many different conditions and cases. Like maybe something like: `except: return_excepted_keys` and that function could return keys that need to be excluded.. – geoboy Aug 02 '16 at 14:45
  • If you wish to build a complex json, consider using [jbuilder](https://github.com/rails/jbuilder). However, it doesn't solve your problem in the way you describe. You need to put all the logic to build json in a separate file with jbuilder. – Canh Aug 03 '16 at 02:55
0

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.

Community
  • 1
  • 1
Joe Woodward
  • 423
  • 3
  • 12
  • Thanks for the links! Ideally, I was hoping for some way to do it in the controller itself rather than have the serializer deal with a bunch of conditions. If nothing else, I'll go for this! – geoboy Aug 02 '16 at 03:15