Mongoid has_many和多个related_to关联

jsu*_*urf 2 ruby-on-rails mongodb mongoid

我有这样的模型关系:

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
Run Code Online (Sandbox Code Playgroud)

FavoriteShow是用户之间的联接表,并且使用user_id和show_id作为外键进行显示。尽管这些外键已经存在,但我仍然收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

现在,我尝试将两个inverse_of:nil都添加到关联中,并添加以下内容,但没有运气:

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
Run Code Online (Sandbox Code Playgroud)

我有这些关系在ActiveRecord中可以很好地工作,但是当切换到Mongoid时,我仍然不清楚应该如何转换确切的关系。任何帮助将非常感激!

Bil*_*tts 5

使用基于文档的数据库(例如MongoDB)时,不需要像关系数据库那样的联接表。我建议一种类似以下的结构:

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
Run Code Online (Sandbox Code Playgroud)