2017-07-24 53 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') 
相关问题