首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >蒙哥德,belongs_to和embedded_in热能行吗?

蒙哥德,belongs_to和embedded_in热能行吗?
EN

Stack Overflow用户
提问于 2012-09-07 13:47:14
回答 1查看 1.6K关注 0票数 2

我有三个模型:用户,图片,和喜欢

其中:

代码语言:javascript
复制
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 )
  • 看看用户制作的是什么样的图片?

实现这三个要求的架构正确吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-07 14:00:09

首先,嵌入模型不能在其他地方引用,就像您已经尝试过在用户中引用like (已经嵌入在图片中)一样。

正确的模型结构将是

代码语言:javascript
复制
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

现在回答您的问题

代码语言:javascript
复制
# 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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12319407

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档