2017-07-24 54 views
0

型號的關係:Article belongs_to Author如何更改空的Jbuilder partials的默認行爲?

樣品JBuilder的觀點:

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

當文章沒有作者會發生什麼:

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

問:

有沒有乾淨的方式強制jbuilder顯示null{}當變量傳遞給關聯的模板是空的?這個問題在相當大的應用程序中普遍存在,並且添加像這樣的代碼article.author.empty? ? json.author(nil) : json.author(article.author, partial: 'author', as: :author)無處不是我想要做的事情。也許某種形式的幫手不需要太多的重構?

我不想覆蓋核心jbuilder的功能,因爲我不想破壞它(部分接受多個變量)。

相關JBuilder的問題:https://github.com/rails/jbuilder/issues/350

回答

1

這將完成你想要

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

我會建議一個幫手,雖然避免一切重複的內容:

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 

然後你會稱它爲像這樣:

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