Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract all attributes with Rails Jbuilder?

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?

like image 734
chikaram Avatar asked Apr 12 '14 07:04

chikaram


3 Answers

Maybe you can use json.merge!.

json.merge! notification.attributes

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

like image 175
zato Avatar answered Nov 17 '22 05:11

zato


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

json.(notification, *notification.attributes.keys)
like image 11
jvalanen Avatar answered Nov 17 '22 06:11

jvalanen


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"
   }
}
like image 3
Rahul Singh Avatar answered Nov 17 '22 05:11

Rahul Singh