Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class User < ActiveRecord::Base
- has_many :user_clients, :dependent => true
- has_many :clients, :through => :user_client
- end
- class UserClient < ActiveRecord::Base
- belongs_to :user
- belongs_to :client
- # user_client join table contains :primary column
- after_create :init_primary
- before_destroy :preserve_primary
- def init_primary
- # first association for a client is always primary
- if self.client.user_clients.length == 1
- self.primary = true
- self.save
- end
- end
- def preserve_primary
- if self.primary
- #unless this is the last association, make soemone else primary
- unless self.client.user_clients.length == 1
- # there's gotta be a more concise way...
- if self.client.user_clients[0].equal? self
- self.client.user_clients[1].primary = true
- else
- self.client.user_clients[0].primary = true
- end
- end
- end
- end
- end
- class Client < ActiveRecord::Base
- has_many :user_clients, :dependent => true
- has_many :users, :through => :user_client
- end
- class Client < AR::B
- has_many :users, :dependent => :destroy
- has_one :primary_contact, :class_name => "User",
- :conditions => {:primary_contact => true},
- :dependent => :destroy
- end
- class User < AR::B
- belongs_to :client
- after_save :ensure_only_primary
- before_create :ensure_at_least_one_primary
- after_destroy :select_another_primary
- private
- # We always want one primary contact, so find another one when I'm being
- # deleted
- def select_another_primary
- return unless primary_contact?
- u = self.client.users.first
- u.update_attribute(:primary_contact, true) if u
- end
- def ensure_at_least_one_primary
- return if self.client.users.count(:primary_contact).nonzero?
- self.primary_contact = true
- end
- # We want only 1 primary contact, so if I am the primary contact, all other
- # ones have to be secondary
- def ensure_only_primary
- return unless primary_contact?
- self.client.users.update_all(["primary_contact = ?", false], ["id <> ?", self.id])
- end
- end
Add Comment
Please, Sign In to add comment