2013-02-18 132 views
17

我有以下型號:Rails嵌套的資源和路由 - 如何分解控制器?

  • 標籤
  • TaggedPost(從郵政和標籤,標籤的has_many獲得其關聯:通過)

和我有以下routes.rb文件:

resources :tags 

resources :posts do 
    resources :tags 
end 

所以當我n例如/posts/4/tags,這將使我在參數數組中設置post_id值的情況下,將我帶入標籤控制器的索引操作。涼。

雖然我的問題是,現在我正在訪問帖子下的嵌套標籤資源,我應該點擊標籤控制器嗎?或者我應該設置一些其他控制器來處理此時標籤的嵌套特性?否則,我必須在標籤控制器中增加額外的邏輯。這當然可以完成,但這是處理嵌套路由和資源的常見方式嗎?我在爲標籤控制器index操作的代碼如下:

TagsController.rb

def index 
    if params[:post_id] && @post = Post.find_by_id(params[:post_id]) 
    @tags = Post.find_by_id(params[:post_id]).tags 
    else 
    @tags = Tag.order(:name) 
    end 
    respond_to do |format| 
    format.html 
    format.json {render json: @tags.tokens(params[:q]) } 
    end 
end 

我可以看到在這個控制器的代碼變得越來越大,因爲我計劃了很多額外的與標籤資源相關聯的資源。如何解決這個問題的想法?

總結的問題:

  1. 如果資源被嵌套,如果嵌套的資源是通過代表的資源的嵌套性質不同的控制器去?這與我提供的代碼示例中的正常控制器相反。
  2. 如果是這樣,這些控制器應該如何命名和設置?

讓我知道你是否需要更多信息。

回答

4

所有你正在做的嵌套資源正在改變路由URL。唯一需要做的事情是確保將正確的身份證(在您的個人信息中)傳遞給標籤控制器。最常見的錯誤是無法找到*** ID。

,如果你不嵌套的輪廓路徑到用戶的路線就應該是這樣的

domain.com/user/1

domain.com/profile/2

當你巢路線這將是

domain.com/user/1/profile/2

這是所有它在做什麼。沒有其他的。你不需要額外的控制器。做嵌套路由只是爲了看起來。讓您的用戶關注關聯。關於嵌套路線最重要的事情是,你要確保你的link_to是正確的路徑。

沒有嵌套時:這將是user_path和profile_path

當它被嵌套,你將需要使用user_profile_path。

耙路是您的朋友,瞭解路線如何變化。

希望它有幫助。

+0

這實際上回答了我的問題的核心......我想除此之外的物流真的取決於我強迫組織的需求。 – 2013-02-18 23:15:31

+0

請爲了你未來的同事(和你自己!),請閱讀@lazel答案! – gfd 2016-12-13 16:00:27

+0

打算在這個投票中花費一些辛苦賺取的點數。請添加嵌套控制器。 – Drenmi 2017-11-26 14:08:55

29

我認爲最好的辦法是分裂控制器:

resources :tags 

    resources :posts do 
     resources :tags, controller: 'PostTagsController' 
    end 

然後你有3個控制器。或者,你可以從TagsController繼承 PostTagsController做這樣的事情:

class PostTagsController < TagsController 
     def index 
      @tags = Post.find(params[:post_id]).tags 
      super 
     end 
    end 

如果差別僅僅是標籤的檢索,您可以:

class TagsController < ApplicationController 
     def tags 
      Tag.all 
     end 

     def tag 
      tags.find params[:id] 
     end 

     def index 
      @tags = tags 
      # ... 
     end 
     # ... 
    end 

    class PostTagsController < TagsController 
     def tags 
      Product.find(params[:product_id]).tags 
     end 
    end 

使用方法和簡單地重寫標籤在繼承控制器;)

+1

這個答案是更清潔,更容易理解任何即將到來的同事恕我直言。我知道Rails是關於DRY的,但在這種情況下,OP說'我計劃將許多額外的資源與標籤資源相關聯,以便區分每個關聯可能會很有幫助... – gfd 2016-12-13 15:51:30

+1

現在在控制器選項中我們應該有'post_tags'。 http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use – 2018-01-08 11:04:30