首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何更改空Jbuilder部分的默认行为?

如何更改空Jbuilder部分的默认行为?
EN

Stack Overflow用户
提问于 2017-07-24 12:34:46
回答 1查看 1.6K关注 0票数 0

模型关系:Article belongs_to Author

示例jbuilder视图:

代码语言:javascript
复制
json.extract! article,
  :id,
  :created_at,
  :updated_at
json.author article.author, partial: 'author', as: :author

当文章没有作者时会发生什么:

代码语言:javascript
复制
{
   "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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-24 14:49:28

这将实现你想要的。

代码语言:javascript
复制
json.author do
  if article.author.blank?
    json.null!
  else
    json.partial! 'authors/author', author: article.author
  end
end

不过,为了避免重复,我建议找个帮手:

代码语言:javascript
复制
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

然后你会这样称呼它:

代码语言:javascript
复制
json_partial_or_null(json, name: 'author', local: :author, object: article.author, partial: 'authors/author')
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45280793

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档