2

私には3つのモデルがあります:ユーザー、画像、いいね

どこ:

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)
  • ユーザーがどのような絵を描くのか見てみましょう。

このスキーマは、3つの要件を達成するために正しいですか?

4

1 に答える 1

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
于 2012-09-07T14:00:09.147 に答える