2

I have three Models: User, Picture, and Like

where:

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

No I want to store the likes to then:

  • See how many likes have a picture ( Picture.first.likes.count )
  • See how many likes a user has ( User.first.likes.count )
  • See to what picture the user make a like?

Is this Schema correct to achieve the three requires?

Linger
  • 14,942
  • 23
  • 52
  • 79
matiasfha
  • 1,270
  • 4
  • 23
  • 42

1 Answers1

2

First thing the embedded model can't be referenced in other like you have tried for Like(which is already embedded in picture) to be referenced in User.

The correct model structure will be

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

now answer to your queries

# 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
Mohamad
  • 34,731
  • 32
  • 140
  • 219
abhas
  • 5,193
  • 1
  • 32
  • 56