带条件的 Rails as_json [英] Rails as_json with conditions

查看:40
本文介绍了带条件的 Rails as_json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my application, :foos have many :bars, and I'm serializing each foo as JSON like so:

@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 } 
  ]
}

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

As you can see, my serialized hash includes an inactive bar. How can I exclude inactive bars from my hash?

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

It would be great if I could do this:

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

我是否已经尽可能地使用 as_json ?我现在需要切换到活动模型序列化程序吗?

Have I taken as_json as far as it will go? Do I need to switch to active model serializers now?

推荐答案

我想你可以尝试添加一些像 active_bars 这样的方法,它会准确地返回你需要的东西:

I think you could try add some method like active_bars which will return exactly what you need like:

def active_bars
  bars.where active: true
end

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

or you could even add new relation:

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] }
  }
)

这篇关于带条件的 Rails as_json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆