Skip to content

Instantly share code, notes, and snippets.

@harlow
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harlow/63915b8754eb423296c1 to your computer and use it in GitHub Desktop.
Save harlow/63915b8754eb423296c1 to your computer and use it in GitHub Desktop.
Assigning cases to users. A de-factoring of https://gist.github.com/dhh/9348053
class Case::AssignmentsController < ApplicationController
before_action :set_case, :set_new_owner
def create
ActiveRecord::Base.transaction do
# update case owner
@case.update! case_params.merge(owner: @new_owner)
# transfer open tasks to new owner
@case.tasks.open.each { |task| task.update!(owner: @new_owner) }
# create `initial` task
if create_initial_contact_task?
@case.tasks.create!(kind: :initial, comments: comments)
end
# record the event
@case.events.create! activity_params.merge(activity: :assigned, creator: @current_user)
end
end
private
def set_case
@case = @current_account.cases.find(params[:case][:id])
end
def set_new_owner
@new_owner = @current_account.users.find(params[:case][:owner_id])
end
def create_initial_contact_task?
!!params.require(:case).permit(:require_initial) && @new_owner.tasks.initials?
end
def case_params
params.require(:case).permit(:distribute_at, :distribute_rule_name)
end
def activity_params
params.require(:case).permit(:comments)
end
end
class Event < ActiveRecord::Base
belongs_to :eventable, polymorphic: true
store_accessor :details, :activity, :creator, :comments
end
class Task < ActiveRecord::Base
belongs_to :user
belongs_to :case
enum status: [:open, :closed]
has_many :events, as: :eventable
end
class User
has_many :tasks do
def initials?
where(kind: :initial).exist?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment