Pergunta

I have model relationships like so:

class User
  include Mongoid.Document

  has_many :favorite_shows
end

class FavoriteShow
  include Mongoid.Document

  belongs_to :user
  belongs_to :show
end

class Show
  include Mongoid.Document

  has_many :favorite_shows
end

FavoriteShow is a join table between users and shows with both the user_id and show_id as foreign keys. I keep getting the following error despite the fact that these foreign keys already exist:

Problem:
         When adding a(n) Show to User#favorite_shows, Mongoid could not determine the inverse foreign key to set. The attempted key was 'user_id'.
       Summary:
         When adding a document to a relation, Mongoid attempts to link the newly added document to the base of the relation in memory, as well as set the foreign key to link them on the database side. In this case Mongoid could not determine what the inverse foreign key was.
       Resolution:
         If an inverse is not required, like a belongs_to or has_and_belongs_to_many, ensure that :inverse_of => nil is set on the relation. If the inverse is needed, most likely the inverse cannot be figured out from the names of the relations and you will need to explicitly tell Mongoid on the relation what the inverse is.

        Example:
          class Lush
            include Mongoid::Document
            has_one :whiskey, class_name: "Drink", inverse_of: :alcoholic
          end

          class Drink
            include Mongoid::Document
            belongs_to :alcoholic, class_name: "Lush", inverse_of: :whiskey
          end

Now I've tried adding both inverse_of: nil to the associations, as well as the following with no luck:

class User
  include Mongoid.Document

  has_many :favorite_shows, class_name: "FavoriteShow", inverse_of: :user
end

class FavoriteShow
  include Mongoid.Document

  belongs_to :user, class_name: "User", inverse_of: :favorite_shows
  belongs_to :show, class_name: "Show", inverse_of: :favorite_shows
end

class Show
  include Mongoid.Document

  has_many :favorite_shows, class_name: "FavoriteShow", inverse_of: :favorite_shows
end

I have these relationships working perfectly in ActiveRecord, but when switching over to Mongoid, I'm still unclear how the exact relationship is supposed to be translated. Any help would be really appreciated!

Foi útil?

Solução

When using a document based database such as MongoDB you don't have a need for join tables like you would with a relational database. I suggest a structure like the one below:

class User
  include Mongoid::Document
  include Mongoid::Timestamps

  has_and_belongs_to_many :favorite_shows, class_name: "Show", inverse_of: :users
end

class Show
  include Mongoid::Document
  include Mongoid::Timestamps

  has_and_belongs_to_many :users, class_name: "User", inverse_of: :favorite_shows
end
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top