How to extract all attributes with Rails Jbuilder?

chikaram picture chikaram · Apr 12, 2014 · Viewed 12.9k times · Source

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?

Answer

zato picture zato · May 2, 2014

Maybe you can use json.merge!.

json.merge! notification.attributes

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