我有一个User模型,一个Book模型,一个Author模型和一个Authorship模型。用户has_many书籍,书籍属于用户。本书has_many:作者通过:作者身份。
要记住的重要一点是,作者不要创作书籍。用户创建书籍,并为书籍分配1个或多个作者。 (作者模型只有一个名称列)
现在我想要这样的路线:
/authors # all authors index
/authors/1/books # all books with this author
/users/3/authors # all authors used by user's books
# should this be /users/3/books/authors ???
/users/3/author/1/books # all books with author id=1 made by user with ID=3
这是我想出的,有人可以解释我哪里出错了以及如何纠正它?非常感谢。
的routes.rb
resources :authors do
member do
get :books
end
end
resources :users do
resources :authors do
member do
get :books
end
end
end
答案 0 :(得分:1)
将书籍变成资源:
resources :authors do
resources :books
end
resources :users do
resources :authors do
resources :books
end
end
棘手的是你的书籍/作者控制器中的索引动作:
您必须检查是否提供了user_id并相应地加入:
作者控制者:
class AuthorsController < ApplicationController
def index
if params[:user_id]
# authors used by this user's books
@authors = Author.joins(:authorships).joins('INNER JOIN books ON books.id = authorships.book_id').where(['books.user_id = ?', params[:user_id]]).group('authors.id')
else
# all authors
@authors = Author.all
end
end
end
BooksController:
class BooksController < ApplicationController
def index
if params[:user_id] && params[:author_id]
# all books with :author_id made by :user_id
@books = Book.joins(:authorships).where(['authorships.author_id = ?', params[:author_id]], ['books.user_id = ?', params[:user_id]])
elsif params[:author_id]
# all books with :author_id
@books = Book.joins(:authorships).where(['authorships.author_id = ?', params[:author_id]])
else
# all books
@books = Book.all
end
end
end