【问题标题】:How to change default behavior of empty Jbuilder partials?如何更改空 Jbuilder 部分的默认行为?
【发布时间】:2017-12-30 01:14:12
【问题描述】:

模型关系: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

【问题讨论】:

    标签: ruby-on-rails json ruby partials jbuilder


    【解决方案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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      相关资源
      最近更新 更多