2012-01-18 139 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