2011-07-29 35 views
1

我有用戶模型,書籍模型,作者模型和作者模型。用戶has_many書籍,以及書籍屬於用戶。書has_many:作者通過:authorhips。鐵路3路由:遇到麻煩了解有多個關聯的路由

重要的是要記住的是作者不要創建書籍。用戶創建書籍,並將一個或多個作者分配到書中。 (作者模型只是有一個名字列)

現在我想的路線是這樣的:

/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 
+1

「我要去哪裏錯了」 如果能分享什麼不順心,它是如何出錯,可能是分享一些日誌信息,這將是一個很大更容易幫助你。 – DallaRosa

回答

1

把書變成資源:

resources :authors do 
    resources :books 
end 

resources :users do 
    resources :authors do 
    resources :books 
    end 
end 

棘手的事情是在你的書籍/作者控制器index操作:

你必須檢查是否提供user_id並加入:

作者Cont輥:

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 
+0

哈謝謝,你完全正確我自己遇到了這個! –