我有一个API调用,返回以下内容(最简单的形式):
App_Group {
id: 1,
apps: [{
id :1,
status: 'Active'},
{
id :2,
status: 'Retired'}
]
我希望创建一个范围(或者可能是另一个更好的解决方案),允许我(在&active=true
之类的API标志上)过滤嵌套属性apps
以仅显示应用程序状态为“有效”。
经过一些试验和错误,我能想到的最好的是:
scope :active_apps, lambda { |id| joins(:apps).where(apps: {status:'Active'}).where(id:id)}
AppGroup.active_apps(123)
会返回多个结果(应用中每个“有效”属性都有一个),而apps属性中包含每个结果。
有没有办法获得我想要的结果?
谢谢!
答案 0 :(得分:1)
AppGroup模型中的答案是
has_many :apps
#added the following
has_many :active_apps, -> { where(status: 'Active') }, :class_name => 'App'
因此,我没有在AppGroup模型中确定范围,而是在App模型中命名为scoped,我只需在需要时调用它。