【问题标题】:Trying to figure out what kind of relationships I should use试图弄清楚我应该使用什么样的关系
【发布时间】:2012-10-29 21:49:11
【问题描述】:

辛纳特拉,Mongoid 3

有 4 个模型:User, Book, FavoriteBooks, ReadBooks, NewBooks。每个用户都有自己的最爱、阅读和新书列表。一本书属于一个列表。但也可以请求任何书籍的信息,这意味着书籍不应嵌入到FavoriteBooks, ReadBooks, NewBooks

方案部分:

class Book
 include Mongoid::Document
 belongs_to :favourite_books
 belongs_to :read_books
 belongs_to :new_books 
end

class FavoriteBook
 include Mongoid::Document
 has_many :books
end

#.... the same for ReadBooks and NewBooks


class User
 include Mongoid::Document
 # what else?
end

我好像错过了什么。

我应该怎么做才能让用户“包含”FavoriteBooks, ReadBooks, NewBooks 的列表?我应该使用一对一的关系吗?

【问题讨论】:

    标签: ruby mongodb mongoid


    【解决方案1】:

    我认为你应该重新考虑你的建模。恕我直言,它应该是 book 和 user 作为模型,并且 favorite_books、read_books 和 new_books 都应该是这样的关系:

    class User
     include Mongoid::Document
     has_many :favorite_books
     has_many :read_books
     has_many :new_books
    
     has_many :books, :through => :favorite_books
     has_many :books, :through => :read_books
     has_many :books, :through => :new_books
    end
    
    class Book
     include Mongoid::Document
     has_many :favorite_books
     has_many :read_books
     has_many :new_books
    
     has_many :users, :through => :favorite_books
     has_many :users, :through => :read_books
     has_many :users, :through => :new_books 
    end
    
    class FavoriteBook
     include Mongoid::Document
     belongs_to :books
     belongs_to :users
    end
    
    #.... the same for ReadBooks and NewBooks
    

    我认为这应该是一个更好的方法。 =)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多