通过其关联模型的属性对Mongoid对象进行排序

时间:2012-10-03 07:01:33

标签: ruby-on-rails mongodb mongoid

我在尝试理解Mongoid如何进行排序时遇到了一些问题。我有两个模型,Gig和Venue,两者都通过belongs_to has_many关系关联。

我正试图通过Venue对象的属性“name”对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

1 个答案:

答案 0 :(得分:0)

你不能加入mongo。如果需要连接,请使用关系数据库。非关系数据库的“特性”是您不能进行连接。

您基本上有两种选择:

  1. 一个before_save回调,它会将场地名称作为附加字段注入演出(例如参见https://github.com/rewritten/timebank/blob/master/lib/mongoid/denormalize.rb

  2. map-reduce任务,在任何场地或演出的任何修改之后,会将场地名称更新为演出作为附加字段。

  3. 最后,您需要Gig系列中的一个字段来订购它。

相关问题