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

上のメソッドを使用して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 に答える