【问题标题】:Is there any way to hide attributes in a Rails Jbuilder template?有什么方法可以隐藏 Rails Jbuilder 模板中的属性?
【发布时间】:2016-11-13 21:48:12
【问题描述】:

我知道你可以像这样明确列出字段,

json.(model, :field_one, :field_two, :field_three)

但是有没有类似下面的,

json.(model, except: :field_two)

哪个会输出除被调出的模型字段之外的所有模型字段?

【问题讨论】:

  • 你试过json.merge! model.attributes.except("field_one", "field_two")吗?
  • @mmichael 成功了!似乎有更简单的方法...

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


【解决方案1】:

对于非 ActiveRecord 对象,这种类似的模式适用(Rails 4)

 json.merge! @some_object.as_json.except("not_this_one")

【讨论】:

    【解决方案2】:

    这颗宝石正是你所需要的。

    json.except! @resource, :id, :updated_at

    https://github.com/chenqingspring/jbuilder-except

    【讨论】:

      【解决方案3】:

      试试json.merge! model.attributes.except("field_one", "field_two")

      【讨论】:

        【解决方案4】:

        我曾经做过这样的事情。 获取模型所有所需属性的数组

        model.attributes.keys.map { |key| key.to_sym } - [:field_one, :field_two]
        

        可以这样写

         model.attributes.keys.map(&:to_sym) - [:field_one, :field_two]
        

        然后在传入 jbuilder 的同时 splat 数组

        json.(model, *(model.attributes.keys.map(&:to_sym) - [:field_one, :field_two]))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-06-25
          • 2011-07-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多