igmarin
6/24/2014 - 5:32 PM

Complex Cities Controller

Complex Cities Controller

class CitiesController < ApplicationController
  load_and_authorize_resource
  before_filter :authenticate_user!, :except => [:participants]
  before_filter :load_city, except: [:new, :create]

  def new
    @city = City.new
    @city.build_profile
  end

  def create
    @city = City.new(params[:city])
    @city.suggested_by = current_user

    if @city.save
      redirect_to root_path, notice: 'The city you suggested was successfully saved, however the information will be validated before it goes public.'
    else
      render action: 'new'
    end
  end

  def follow
    current_user.follow_city(@city)
    flash[:notice] = "You are now following #{@city.name}"
    redirect_to :back
  end

  def unfollow
    current_user.unfollow_city(@city)
    flash[:notice] = "You are no longer following #{@city.name}"
    redirect_to :back
  end

  def participate
    participation = CityParticipation.new(@city)
    participation.add_participant(current_user)
    participation.add_follower(current_user)
    flash[:notice] = "You are now participating in #{@city.name}"
    redirect_to :back
  end

  def participants
    @participants = @city.users
  end

  def events
    @events = @city.sections.find_by_name("events").section_items
  end

  def vote_admin
    # flash.clear
    representatives = @city.users.representatives
    @representatives = representatives.where('id not IN (?)', current_user.id)
    if representatives.count < 5
      redirect_to root_url(subdomain: @city.slug), notice: 'This city has to have at least five representatives to access the admin selection poll'
    else
      @city_vote = CityVote.new
    end
  end

  def create_vote_admin
    representative = @city.users.representatives.where(id: params[:city_vote][:representative_id]).first
    city_vote = CityParticipation.new(@city).vote_for_representative_as_admin(representative, current_user)
    if city_vote
      flash[:notice] = "Your vote was successfully saved."
    else
      flash[:alert] = "Oops! Your vote was not saved, please try again."
    end
  end

  def leave
    CityParticipation.new(@city).remove_participant(current_user)
    flash[:notice] = "You are no longer participating in #{@city.name}"
    redirect_to :back
  end

  def edit
    redirect_to root_path, alert: 'You are not authorized to access this resource.' unless current_user.superadmin_or_admin_for_city(@city)
  end

  def update
    if @city.update_attributes(params[:city])
      flash[:notice] = "City successfully saved."
    else
      flash[:alert] = "City wasn't saved."
    end

    render action: :edit
  end

  private
  def load_city
    @city = City.find(params[:id])
  end
end