2012-09-07 21 views
2

我有三個模式:用戶,圖片,像Mongoid,belongs_to和embedded_in hot可以做id嗎?

其中:

class Picture 
    include Mongoid::Document 
    embeds_many :likes 
    belongs_to :user 
end 
class User 
    include Mongoid::Document 
    has_many :pictures 
    has_many :likes 
end 
class Like 
    include Mongoid::Document 
    belongs_to :user 
    embedded_in :picture 
end 

不,我想喜歡存儲則:

  • 看看有多少喜歡有他的照片( Picture.first.likes.count)
  • 查看有多少用戶喜歡(User.first.likes.count)
  • 看看用戶做了什麼樣的圖片?

這個模式是否正確地實現了三個要求?

回答

2

首先,嵌入式模型無法在其他引用中使用,例如您已嘗試在User中引用Like(已嵌入圖片中)。

正確的模型結構將

class Picture 
    include Mongoid::Document 
    has_and_belongs_to_many :likers, :class_name => "User", :inverse_of => nil 
    belongs_to :user 
end 

class User 
    include Mongoid::Document 
    has_many :pictures 
end 

現在回答您的查詢

# See how many likes have a picture 
Picture.first.likers.count 
# See how many likes a user has 
# (assumption - will have only one like from one user for a specific picture) 
Picture.where(:liker_ids => User.first).count 
# See to what picture the user make a like? 
Picture.where(:liker_ids => User.first).all 
+0

非常感謝..這項工作做得很好:d – matiasfh