Search code examples
ruby-on-railsjbuilder

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?


Solution

  • Maybe you can use json.merge!.

    json.merge! notification.attributes
    

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