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

时间:2016-07-11 20:20:26

标签: ruby-on-rails ruby json ruby-on-rails-5 jbuilder

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?

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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]))

答案 2 :(得分:0)

这个宝石就是你所需要的。

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

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

答案 3 :(得分:0)

对于非ActiveRecord对象,此类似模式有效(Rails 4)

 json.merge! @some_object.as_json.except("not_this_one")