2012-10-03 82 views
1

我在嘗試理解Mongoid如何排序時遇到了一些問題。我有2個模型,Gig和Venue,它們都通過belongs_to has_many關係關聯。通過其關聯模型的屬性對Mongoid對象排序

我想通過Venue對象的屬性'名稱'來排序Gig的對象無濟於事。

我希望有人能夠指出我正確的方向。

下面是截斷的模型描述。

我的查詢也低於:

# Gig Model 
class Gig 
    include Mongoid::Document 
    include Mongoid::Paperclip 
    include SearchMagic 

    belongs_to :owner, :class_name => "User", :inverse_of => :owns 
    belongs_to :venue 

    has_and_belongs_to_many :attenders, :class_name => "User", :inverse_of => :attending 

    has_and_belongs_to_many :artistes 

<snip> 
end 

# Venue Model 
class Venue 
    include Mongoid::Document 
    include Mongoid::Paperclip 
    include SearchMagic 

    has_many :gigs 
    field :foursquare_id, type: String 
    embeds_one :address 
    embeds_many :user_ratings 

    field :facebook, type: String 
    field :twitter, type: String 
    field :website, type: String 
    field :name, type: String 
    field :postal, type: String 
    field :tel, type: String 
    field :venue_type, type: String 
    field :description, type: String 
    field :rating, type: Float, default: 0.0 

<snip> 
end 


# Console 

>> Gig.desc('venue.name').map{|f| f.venue.name}            
=> ["*SCAPE", "Velvet Underground", "Blujaz Lounge", "Velvet Underground", "Home Club", "Wh 
ite House, Emily Hill", "Zouk", "Zouk", "The Pigeonhole", "Home Club", "Home Club", "Home C 
lub"] 

# sorting doesn't work 

回答

0

不能在蒙戈加入。如果您需要連接,請使用關係數據庫。非關係數據庫的「特徵」是你不能進行連接。

你有兩種基本的選擇:

  1. 一個before_save回調,這將注入會場到演出作爲附加字段的名稱(例如見https://github.com/rewritten/timebank/blob/master/lib/mongoid/denormalize.rb

  2. 一個MAP-減少任何場地或演出任何修改後的任務,將場地名稱更新爲演出作爲附加領域。

最後,您需要Gig集合中的一個字段來訂購它。

相關問題