Is there any way to hide attributes in a Rails Jbuilder template?
Asked Answered
C

4

7

I know you can explicitly list fields like so,

json.(model, :field_one, :field_two, :field_three)

But is there anything similar to the following,

json.(model, except: :field_two)

which would output all of the model fields except the one called out?

Cytology answered 11/7, 2016 at 20:20 Comment(2)
Have you tried json.merge! model.attributes.except("field_one", "field_two")?Devora
@mmichael that worked! Seems like there'd be an easier way ...Cytology
D
12

Try json.merge! model.attributes.except("field_one", "field_two")

Devora answered 11/7, 2016 at 20:51 Comment(0)
M
1

I had done something like this. Get an array of all desired attributes of model

model.attributes.keys.map { |key| key.to_sym } - [:field_one, :field_two]

Which can be written like

 model.attributes.keys.map(&:to_sym) - [:field_one, :field_two]

Then splat the array while passing in jbuilder

json.(model, *(model.attributes.keys.map(&:to_sym) - [:field_one, :field_two]))
Majormajordomo answered 11/7, 2016 at 20:48 Comment(0)
S
1

For non ActiveRecord objects this similar pattern works (Rails 4)

 json.merge! @some_object.as_json.except("not_this_one")
Spiritualty answered 26/10, 2017 at 14:1 Comment(0)
A
0

This gem is what you need.

json.except! @resource, :id, :updated_at

https://github.com/chenqingspring/jbuilder-except

Ahouh answered 22/8, 2017 at 1:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.