[英]Rails: Two different many to many relationships between two models
I have two tables named books (id, name, author_name)
and users (id, name, location)
. 我有两个表,分别是books (id, name, author_name)
和users (id, name, location)
。 A book can either be viewed by a user or edited by a user. 书籍可以由用户查看或由用户编辑。 So, for these two relationships I have two join tables viz. 因此,对于这两个关系,我有两个联接表。 book_editor_users (book_id, user_id)
and book_viewer_users (book_id, user_id)
. book_editor_users (book_id, user_id)
和book_viewer_users (book_id, user_id)
。 How do I model this in Rails such that I can retrieve editor users and viewer users like this: 如何在Rails中对此建模,以便我可以像这样检索编辑器用户和查看器用户:
Book.find(1).book_editor_users
Book.find(1).book_viewer_users
My attempt for the book and user model are: 我对本书和用户模型的尝试是:
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
Join models I have written are: 我编写的联接模型是:
class BookEditorUser < ActiveRecord::Base
belongs_to :book
belongs_to :user
end
class BookViewerUser < ActiveRecord::Base
belongs_to :book
belongs_to :user
end
There is another work around that I thought of, but I am not sure whether it is the Rails way. 我想到了另一种解决方法,但是我不确定这是否是Rails方式。 That work around is to have a single join table book_users (book_id, user_id, type)
where the type column can capture whether it is an editor relationship or a viewer relationship. 解决方法是只有一个book_users (book_id, user_id, type)
表book_users (book_id, user_id, type)
,其中type列可以捕获是编辑器关系还是查看器关系。
Single joining table(books_users) is the best way for doing this with permission column in it. 单个连接表(books_users)是在其中具有权限列的最佳方法。 Lets say integer column with 1 for view 2 for edit(3 for both if it could be a possibilty). 假设对于视图2来说,带有1的整数列对于edit来说(如果可能的话,对于两个都是3)。 And to get editor or viewer users you should write scope in their joining model(BooksUsers) 要获得编辑者或查看者用户,您应该在其加入模型中写入范围(BooksUsers)
scope :viewers, -> { where(permission: 1) }
scope :editors, -> { where(permission: 2) }
now you can find books particular user from these scope 现在您可以从这些范围中找到特定用户的书籍
Book.find(1).books_users.viewers
Book.find(1).books_users.editors
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.