是否有更清洁的方法来实现这一目标?

Pau*_*ane 2 ruby-on-rails

我试图只根据传递的不同信息显示表中的某些记录,如果没有满足任何要求,它会重定向到主页.代码全部正常运行,只想看看其他人如何解决这个问题

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
Run Code Online (Sandbox Code Playgroud)

Nic*_*nil 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
Run Code Online (Sandbox Code Playgroud)

在你的控制器中:

@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
Run Code Online (Sandbox Code Playgroud)