6

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?

sambecker
  • 1,099
  • 12
  • 28

4 Answers4

10

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

vich
  • 11,836
  • 13
  • 49
  • 66
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]))
Kumar
  • 3,116
  • 2
  • 16
  • 24
0

This gem is what you need.

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

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

user2091375
  • 109
  • 1
  • 3
0

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

 json.merge! @some_object.as_json.except("not_this_one")
aqwan
  • 470
  • 4
  • 6