2012-07-19 169 views
2

im试图根据传递的不同信息从表中显示某些记录,并且如果没有满足任何要求,它将重定向到主页。代码是全部运作,只是想看看其他人会如何解决这个问题有没有更简单的方法来实现这一目标?

if current_user.admin? 
    @schedules = Schedule.all 
elsif current_user.team_id? 
    @schedules = Schedule.find_all_by_team_id(current_user[:team_id]) 
else 
    redirect_to root_path, :status => 301, :alert => "Please contact your club administrator to be assigned to a team." 
    return 
end 
+0

被回答过的问题? – 2012-07-20 01:17:58

回答

6

您应该始终将复杂的逻辑从控制器移开。

class Schedule 
    def self.for(user) 
    case user.role #you should define the role method in User 
     when User::ADMIN 
     scoped 
     when User::TEAM 
     where(team_id: user[:team_id]) 
    end 
    end 
end 

在你的控制器:

@schedules = Schedule.for(current_user) 

redirect_to root_path, :status => 301, :alert => "Please contact your club administrator to be assigned to a team." unless @schedules 
+0

如何添加一个角色比使用'admin?'方法更好?似乎用更多的代码实现相同的结果。 – 2012-07-19 12:39:00

+1

如果您未来有超过两个角色,您可能需要使用case语句。 – 2012-07-19 13:12:11

0

您的问题的一种方法。

@schedules = Schedule.all if current_user.admin? 
@schedules = Schedule.find_all_by_team_id(current_user[:team_id]) if current_user.team_id? 
if @schedules.nil? 
    redirect_to root_path, :status => 301, :alert => "Please contact your club administrator 
    to be assigned to a team." 
else 
    #Your normal redirect 
end 
相关问题