2012-01-18 140 views
0

我有一個users/create控制器操作非常複雜,部分原因是它創建了三種類型的用戶之一,每個用戶都有自己的關聯記錄並設置了需求。想象一下,例如,可以創建WorkerCompanyContractor的表單,並且每個表單都有自己的路由並根據成功與失敗的創建發送自己的電子郵件。跳過和連接控制器代碼部分

儘管最好的意圖,結果是相當數量如下:

if x 
    flash[:notice] = abc 
    redirect_to :action => "new", :layout => "notice" 
elsif y 
    flash[:notice] = def 
    redirect_to :action => "new", :layout => "notice" 
elsif z 
    flash[:notice] = ghi 
    redirect_to :action => "somethingelse", :layout => "else" 
etc. 

我現在有改變重複:action => 'new'的要求又根據PARAMS值的另一目標。

有沒有辦法減少這種冗餘,實際上是說'跳到第2節'?

+0

我不明白你的問題,你是太普通。將所有這些邏輯移至幫助方法將會有所幫助。你的控制器應該保持苗條 –

回答

0

switch/case語句不會這麼做嗎?

switch(val) { 
    case 'x': 
    case 'y': 
    case 'z': 
    // they all perform the same action 
    break; 
} 
0

您可以在您傳遞用戶的位置添加助手方法,並根據其角色輸出相應的消息或路由。這將爲您生成更多代碼,但它可以簡化您的控制器操作。我認爲這取決於你想如何保持組織。

例如,你可以有:

helper_method :new_user_message, :new_user_route 

    def create 
    if @user.save 
     flash[:notice] = new_user_message(@user) 
     redirect_to new_user_route(@user) 
    end 
    end 

    def new_user_message(user) 
    case user.role 
     when x then 'Successful x message' 
     when y then 'Successful y message' 
     when x then 'Successful z message' 
    end 
    end 

    def new_user_route(user) 
    case user.role 
     when x then new_x_path 
     when y then new_y_path 
     when z then new_z_path 
    end 
    end