2014-02-17 17 views
0

My Car模型是JSON序列化的(CarSerializer類< ActiveModel :: Serializer)。但是,對於下面的控制器方法,我只需要DISTINCT列表reserve_ids,如果沒有,AR應該返回空的JSON字符串/數組。我試圖用@cars.blank?無效,因爲無/空數組不返回。請參閱下面的AR對象檢查。Rails - 在單個AR列上序列化'distinct'時返回空的json

def get_reserve_ids 

    # @cars.inspect ==> #<ActiveRecord::Relation [#<Car id: nil, car_reserve_id: nil>]> 
    @cars = Car.select(:car_reserve_id) 
    .where(client_id: current_user.client_id).distinct 

    # @cars.inspect ==> [nil] 
    # @cars = Car.select(:car_reserve_id) 
    # .where(client_id: current_user.client_id).map(&:car_reserve_id).uniq 

    logger.debug @cars.inspect 

    render json: @cars, only: [:car_reserve_id] 

    end 

回答

0

您應該返回@cars.compact - 它將刪除數組中的所有空值,所以您將返回一個空數組。

+0

使用'.map'選項使用!現在我可以測試'if @ cars.blank? render:json => [],status::ok else ...'。謝謝 - 非常感謝! – user1322092

+0

歡迎您!如果我的回答對您有幫助,請將其標記爲已接受。謝謝! –