Mongoid has_many和多个belongs_to关联

时间:2014-05-10 00:32:28

标签: 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

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

现在我已经尝试将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

我有这些关系在ActiveRecord中完美运行,但是当切换到Mongoid时,我仍然不清楚应该如何翻译确切的关系。任何帮助都会非常感激!

1 个答案:

答案 0 :(得分:3)

使用基于文档的数据库(如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