2014-09-02 53 views
1

在我的应用程序as_json,:foos有很多:bars,而我每个序列化作为富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尽可能将何去何从?我现在需要切换到活动模型串行器吗?

回答

3

我想你可以尝试添加像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] } 
    } 
)