How to extract all attributes with Rails Jbuilder?

我的未来我决定 提交于 2019-11-27 06:34:41

问题


It's a pain to write codes like this all the time in jbuilder.json template:

json.extract! notification, :id, :user_id, :notice_type, :message, :resource_type, :resource_id, :unread, :created_at, :updated_at

So I'd like to code like this;

json.extract_all! notification

I've found I can do it like the following codes, but they are still a bit lengthy to me.

notification.attributes.each do |key, value|
  json.set!(key, value)
end

Is there any better way?


回答1:


Maybe you can use json.merge!.

json.merge! notification.attributes

https://github.com/rails/jbuilder/blob/master/lib/jbuilder.rb#L277




回答2:


I'm using jbuilder 1.5.0 and merge! didn't work but I found an alternative syntax:

json.(notification, *notification.attributes.keys)



回答3:


Adding more to @uiureo 's answer

Suppose your Notification has some type of image uploaders (e.g. carrierwave,paperclip)

Then below version will not return you uploader object, so how do you get the image url?

json.merge! notification.attributes

notification.attributes is hash conversion of object, it will return mounted uploader column value but not the url.

sample response

notification: Object {
   title: "hellow world"
   img: "sample.png"
}

Instead try this

json.merge! notification.as_json

This will return mounted column as another object in which you can query for url.

sample response

notification: Object {
   title: "hellow world"
   img: Object {
       url: "https://www.example.com/sample.png"
   }
}



回答4:


You may look at json.except!

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

json.except! @resource

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




回答5:


In case if you want to exclude any of the attributes. Ex: created_at and updated_at

json.merge! notification.attributes.reject{ |key, _| key.in?(['created_at', 'updated_at']) }



回答6:


This is how I do it

json.property  do
  Property.column_names.each do |name|
     json.set! name, @property.try(name)
  end

  # has_ones:
  json.contact @property.contact
end

It's easy to see what's happening, add logic to omit fields etc doing it this way.



来源:https://stackoverflow.com/questions/23027644/how-to-extract-all-attributes-with-rails-jbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!