Mongoid,belongs_to和embedded_in hot can id吗?

时间:2012-09-07 13:47:15

标签: ruby-on-rails mongoid ruby-on-rails-3.2

我有三种型号:用户,图片和类似

其中:

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)
  • 查看用户制作的图片?

这个架构是否正确实现了三个要求?

1 个答案:

答案 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