0

嗨,我只是想知道是否有更简单/合乎逻辑的方式来实现以下目标

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

结尾

4

1 回答 1

1

你可以使用范围

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

您还可以使用 on 方法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
于 2012-10-25T11:49:36.837 回答