嗨,我想知道是否有更简单/逻辑的方式来实现以下
def index
@date = params[:month] ? Date.parse(params[:month]) : Date.today
@schedule = Schedule.new
@players = User.where(:team_id => current_user[:team_id]).all
if current_user.admin?
@schedules = Schedule.all
elsif current_user.manager?
@schedules = Schedule.find_all_by_team_id(current_user[:team_id])
if @schedules.count < 1
redirect_to(root_path, :status => 301, :alert => "This team has no upcoming events<br/> You should add your next event, and TeamMNGT will take care of everything else!".html_safe)
return
end
elsif current_user.team_id?
@schedules = Schedule.find_all_by_team_id(current_user[:team_id])
elsif @schedules.count < 1 and current_user.team_id?
redirect_to(root_path, :status => 301, :alert => "You don't have any upcoming events.<br/> Your team manager has not added any upcoming events for #{@team.name}".html_safe)
return
else
redirect_to root_path, :status => 301, :alert => "Please contact your club administrator to be assigned to a team."
return
end
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @schedules }
end
端
答案 0 :(得分:1)
您可以使用scope。
class Schedule < ActiveRecord::Base
scope :for_user, lambda do |user|
if user.admin?
self # return the relation, you can use all if you want
else
where( team_id: user.team_id )
end
end
end
然后在你的控制器中:
@schedule = Schedule.for_user current_user
if @schedule.blank?
if current_user.admin?
# specific redirect message
elsif current_user.manager?
# specific message
else
# specific redirect message
end
end
您还可以使用User
上的方法为每种类型的用户显示相应的消息(为什么不使用I18n功能):
def blank_schedule_message
# pick a message according to user type, locale ...
end
所以你只需这样做:
if @schedule.blank?
redirect_to root_path, status: 301, alert: current_user.blank_schedule_message
return
end