简体   繁体   中英

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) . 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) . How do I model this in Rails such that I can retrieve editor users and viewer users like this:

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. 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.

Single joining table(books_users) is the best way for doing this with permission column in it. Lets say integer column with 1 for view 2 for edit(3 for both if it could be a possibilty). And to get editor or viewer users you should write scope in their joining model(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM