Search code examples
ruby-on-railsjsonrubypartialsjbuilder

How to change default behavior of empty Jbuilder partials?


Model relation: Article belongs_to Author

Sample jbuilder view:

json.extract! article,
  :id,
  :created_at,
  :updated_at
json.author article.author, partial: 'author', as: :author

What happens when Article has no Author:

{
   "id": 1,
   "created_at": "01-01-1970",
   "updated_at": "01-01-1970",
   "author": []
}

Question:

Is there a clean way to force jbuilder to display null or {} when variable passed to associated template is empty? This problem is prevalent across quite big application and adding code like that article.author.empty? ? json.author(nil) : json.author(article.author, partial: 'author', as: :author) everywhere is not something I'd want to do. Perhaps some form of helper that wouldn't require too much refactoring?

I don't want to override core jbuilder functionality as I don't want to break it (partials accepting multiple variables for example).

Related jbuilder issue: https://github.com/rails/jbuilder/issues/350


Solution

  • This will accomplish what you want

    json.author do
      if article.author.blank?
        json.null!
      else
        json.partial! 'authors/author', author: article.author
      end
    end
    

    I would suggest a helper though to avoid all the duplication:

    module ApplicationHelper
      def json_partial_or_null(json, name:, local:, object:, partial:)
        json.set! name do
          object.blank? ? json.null! : json.partial!(partial, local => object)
        end
      end
    end
    

    Then you would call it like this:

    json_partial_or_null(json, name: 'author', local: :author, object: article.author, partial: 'authors/author')