【问题标题】:Rails as_json with conditions带有条件的 Rails as_json
【发布时间】:2014-10-26 18:04:20
【问题描述】:

在我的应用程序中,:foos 有很多 :bars,我将每个 foo 序列化为 JSON,如下所示:

@foo.as_json(
  except: [:created_at, :updated_at], 
  include: { 
    bars: { only: [:ip_addr, :active] }
  }
)

这给了我以下信息:

{
  "id" => 2, 
  "name" => "Hello World",
  "bars" => [ 
    { "ip_addr" => "192.123.12.32", "active" => 0 }, 
    { "ip_addr" => "192.123.12.33", "active" => 1 } 
  ]
}

如您所见,我的序列化哈希包含一个非活动栏。如何从我的哈希中排除非活动柱?

如果我能做到这一点,那就太好了:

include: { bars: { only: { :active => true }}}

我是否已将as_json 尽其所能?我现在需要切换到活动模型序列化器吗?

【问题讨论】:

    标签: ruby-on-rails serialization


    【解决方案1】:

    您使用 as_json 和条件来为某些操作自定义 json 响应,但为大多数响应所需的默认 json 响应建模序列化程序。

    阅读这些Model_Serializer VS. as_jsonrecord-serializers-from-scratch

    【讨论】:

      【解决方案2】:

      我认为您可以尝试添加一些方法,例如active_bars,它将完全返回您需要的内容:

      def active_bars
        bars.where active: true
      end
      

      或者你甚至可以添加新的关系:

      has_many :active_bars, -> { where active: true }, class_name: '..', foreign_id: '..'
      

      然后你就可以写了:

      @foo.as_json(
        except: [:created_at, :updated_at], 
        include: { 
          active_bars: { only: [:ip_addr, :active] }
        }
      )
      

      【讨论】:

        猜你喜欢
        • 2011-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多