2011-07-29 6 views
1

私はUserモデル、Bookモデル、Authorモデル、Authorshipモデルを持っています。ユーザーはhas_many Booksを持ち、書籍はユーザーに属します。本はhas_many:authors through:authorshipsです。レール3ルーティング:複数のアソシエーションを持つルートの理解に問題があります

覚えておくべき重要なことは、著者DONTが書籍を作成することです。ユーザーは書籍を作成し、その書籍に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 
+1

「私は間違っているつもりだ」 うまくいかWHAT共有することができれば、それは間違ってどのようになる、おそらくいくつかのログ情報を共有し、それはたくさんのだろうあなたを助けるのがより簡単です。 – DallaRosa

答えて

1
は、リソースに本を回す

resources :authors do 
    resources :books 
end 

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

トリッキーな事はあなたの本/著者コントローラ内のindexアクションです:

あなたがチェックする必要がありますuser_idが提供されているかどうかに応じて参加する:

The Authors 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

ハおかげで、あなたはまったく正しかった私はこの自分自身を見つけた! –

関連する問題