Skip to content

Instantly share code, notes, and snippets.

@gregorym
Created November 16, 2011 22:09
Show Gist options
  • Save gregorym/1371626 to your computer and use it in GitHub Desktop.
Save gregorym/1371626 to your computer and use it in GitHub Desktop.
Cakehealth
class User < ActiveRecord::Base
has_and_belongs_to_many :plans, :after_add => :add_enrollment
has_many :enrollments
def coenroll_with(couser)
couser.plans.each do |p|
plans << p
end
end
def cousers
conditions = ["enrollments.plan_id in (?)", plan_ids]
conditions[0] += " AND enrollments.user_id <> ?"
conditions << self.id
User.all(:joins => :enrollments, :conditions => conditions)
end
private
def add_enrollment(plan)
enrollments.create(:plan => plan)
end
end
class Plan < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :enrollments
end
class Enrollment < ActiveRecord::Base
belongs_to :user
belongs_to :plan
end
describe User do
it "should add a user to an enrollment" do
plan = Plan.create(:name => "Aetna PPO")
don = User.create(:name => "Don")
don.plans << plan
don.enrollments.size.should == 1
betty = User.create(:name => "Betty")
betty.coenroll_with(don)
betty.enrollments.size.should == 1
don.cousers.should include(betty)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment