我有三种型号:用户,图片和类似
其中:
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
不,我想存储喜欢的东西:
这个架构是否正确实现了三个要求?
答案 0 :(得分:2)
首先,嵌入式模型无法像其他人一样被引用,就像你在用户中引用的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