【问题标题】:Mongoid, belongs_to and embedded_in hot can id do?Mongoid、belongs_to和embedded_in hot id可以做什么?
【发布时间】:2012-09-07 13:47:14
【问题描述】:
我有三个模型:用户、图片和点赞
地点:
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)
- 查看用户点赞的图片是什么?
这个 Schema 是否正确地实现了这三个要求?
【问题讨论】:
标签:
ruby-on-rails
mongoid
ruby-on-rails-3.2
【解决方案1】:
第一件事,嵌入模型不能在其他用户中引用,就像您尝试在用户中引用 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