Skip to content

Instantly share code, notes, and snippets.

@csexton
Created August 6, 2015 18:04
Show Gist options
  • Save csexton/f765597c6543b739acde to your computer and use it in GitHub Desktop.
Save csexton/f765597c6543b739acde to your computer and use it in GitHub Desktop.
class Admin::TeamsController < ApplicationController
before_action :authenticate_admin!
def index
unless params[:q].blank?
term = "%#{params[:q]}%"
@team_list = Team.where "name LIKE ?", term
end
end
def edit
@team = Team.find params[:id]
unless params[:q].blank?
term = "%#{params[:q]}%"
@user_list = User.where "email LIKE ? OR first_name LIKE ? OR last_name LIKE ?", term, term, term
end
end
# LOL RESTFUL
# This is more like an add user rpc o.O
def create
user = User.find params[:user_id]
team = Team.find params[:id]
team.member_users << user unless team.has_member?(user)
if params[:add_owner]
team.owner_users << user unless team.owned_by?(user)
end
team.save!
redirect_to admin_edit_team_url(team),
notice: "#{user.name} was added to #{team.name}."
end
def update
team = Team.find params[:id]
changed_user_ids = diff_ids(team.member_user_ids, team_params[:member_user_ids])
if team.update(team_params)
# Cache buster
User.where(id: changed_user_ids).update_all(updated_at: Time.zone.now)
redirect_to admin_edit_team_url(team), notice: 'Team was successfully updated.'
else
render :edit
end
end
private
def diff_ids(existing, incoming)
a = (existing || []).map(&:to_i)
b = (incoming || []).map(&:to_i)
added_ids = a - b
removed_ids = b - a
added_ids + removed_ids
end
def team_params
params.require(:team).permit(:name, owner_user_ids: [], member_user_ids: [])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment