2011-05-29 82 views
2

我正在使用Mongoid來存儲一系列地理編碼列表。這些列表需要按價格和鄰近度進行排序。每個列表的價格都是數據庫中的一個字段,而距離是一個動態屬性,對每個用戶都是唯一的。如何通過Mongoid中的動態屬性訂購文檔

class Listing 
    include Mongoid::Document 

    field :price 

    def distance 
    get_distance(current_user.location,coordinates) 
    end 
end 

如何根據距離對這些文檔進行排序?我試過@listing.desc(:distance),但沒有奏效。

回答

2

簡短的(和無益的)答案是:你不能。

Mongoid確實有能力query based on 2d co-ordinates雖然,那麼你可以更新你的控制器做這樣的事情:

@listings = Listing.near(current_user.location) 

我相信這將在距離順序返回您的物品。

在附註中,我注意到您的Listing模型指的是您的current_user對象,它違反了MVC架構,因爲您的模型不應該知道當前會話的任何內容。