模型关系:Article belongs_to Author
示例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
发布于 2017-07-24 14:49:28
这将实现你想要的。
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')https://stackoverflow.com/questions/45280793
复制相似问题