我有两个名为books (id, name, author_name)
和的表users (id, name, location)
。书籍可以由用户查看或由用户编辑。因此,对于这两个关系,我有两个联接表。book_editor_users (book_id, user_id)
和book_viewer_users (book_id, user_id)
。如何在Rails中对此建模,以便我可以像这样检索编辑器用户和查看器用户:
Book.find(1).book_editor_users
Book.find(1).book_viewer_users
我对本书和用户模型的尝试是:
class Book < ActiveRecord::Bas
has_many :book_editor_users
has_many :users, through: :book_editor_users
has_many :book_viewer_users
has_many :users, through: :book_viewer_users # I am confused on how to setup this line
end
class User < ActiveRecord::Base
has_many :books, through: :book_editor_users
has_many :books, through: :book_viewer_users # I am confused here too
end
我编写的联接模型是:
class BookEditorUser < ActiveRecord::Base
belongs_to :book
belongs_to :user
end
class BookViewerUser < ActiveRecord::Base
belongs_to :book
belongs_to :user
end
我想到了另一种解决方法,但是我不确定这是否是Rails方式。解决方法是只有一个联接表book_users (book_id, user_id, type)
,在该表中,type列可以捕获是编辑器关系还是查看器关系。
单个联接表(books_users)是在其中具有权限列的最佳方法。假设对于视图2来说,带有1的整数列对于edit(如果可能的话,对于两个都是3)。为了获得编辑者或查看者用户,您应该在其加入模型中写入范围(BooksUsers)
scope :viewers, -> { where(permission: 1) }
scope :editors, -> { where(permission: 2) }
现在您可以从这些范围中找到特定用户的书籍
Book.find(1).books_users.viewers
Book.find(1).books_users.editors
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句