2014-02-13 57 views
5

我想知道什麼是解決以下問題的正確方法。如何管理嵌套和非嵌套資源

我有兩個型號:

Publisher and Issue. Publisher has_many issues. 

我要同時管理從發佈列表和問題清單的問題。

例如:

  • 對發佈者列表中,用戶可以點擊放置在每個出版商附近鏈接「問題」。然後他轉到問題列表,但僅針對正確的發佈者進行過濾。他可以點擊「創建新的問題」,去形成新的問題。在這種形式上,我不需要向他展示選擇列表以選擇發佈者

  • 關於問題列表用戶可以單擊「創建新問題」並轉到表單,但是這次他應該從select中選擇發佈者,這將是與創建的問題有關。

簡而言之,我需要針對問題和發佈商問題的粗暴行動。

首先,我儘量做到:

resources :issues 

    resources :publishers do 
    resources :issues 
    end 

,並在發行控制器:

before_filter :find_issue 

def find_issue 
@publisher = Publisher.find(params[:publisher_id]) if params[:publisher_id] 
@issues = @publisher ? @publisher.issues : Issue 
end 

,但我必須做出許多假設條件我的意見和控制器。

例如,如果問題是從發佈者創建的,在成功時我想重定向到publisher_issues_path而不是issue_path,反之亦然。與「回到列表」等類似的所有鏈接都存在同樣的問題。所以代碼在我看來不是很透明。

現在我想知道使用命名空間。

namespace :publishers, do 
    resources :issues 
end 

和使

# app/controllers/publishers/issues_controller.rb 
module Publishers 
    class IssuesController < ApplicationController 
    # actions that expect a :publisher_id param 
    end 
end 

# app/controllers/issues_controller.rb 
class IssuesController < ApplicationController 
    # your typical actions without any publisher handling 
end 

,併爲這兩個控制器操作單獨的視圖。

有沒有更好的或更清潔的方法來解決這類問題?我想盡可能讓代碼變幹。 非常感謝您的回覆。

回答

3

路線:

resources :issues 
resources :publishes do 
    resources :issues 
end 

控制器:

class IssuesController < ApplicationController 
    before_filter :build_issue, only: [:new, :create] 
    before_filter :load_issue, only: [:show, :edit, :update, :destroy] 

    def index 
    @issues = issues.page(params[:page]) 
    end 

    ... all other actions will have access to @issue 

private 
    def issues 
    if params[:publisher_id].present? 
     Publisher.find(params[:publisher_id]).issues 
    else 
     Issue 
    end 
    rescue ActiveRecord::RecordNotFound 
    redirect_to issues_path(alert: 'Publisher not found') 
    end 

    def build_issue 
    @issue = issues.new(issue_params) 
    end 

    def load_issue 
    @issue = issues.find(params[:id]) 
    rescue ActiveRecord::RecordNotFound 
    redirect_to issues_path(alert: 'Issue not found') 
    end 

    def issue_params 
    # whitelisted attributes goes here 
    end 
end 

要避免使用條件,使用的行爲,而不是完整的命名路徑,即:

redirect_to action: :index 
link_to 'Issues', {action: :index}