Guest User

Untitled

a guest
Jun 20th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. class User < ActiveRecord::Base
  2. has_many :user_clients, :dependent => true
  3. has_many :clients, :through => :user_client
  4.  
  5. end
  6.  
  7. class UserClient < ActiveRecord::Base
  8.  
  9. belongs_to :user
  10. belongs_to :client
  11.  
  12. # user_client join table contains :primary column
  13.  
  14. after_create :init_primary
  15. before_destroy :preserve_primary
  16.  
  17. def init_primary
  18. # first association for a client is always primary
  19. if self.client.user_clients.length == 1
  20. self.primary = true
  21. self.save
  22. end
  23. end
  24.  
  25. def preserve_primary
  26. if self.primary
  27. #unless this is the last association, make soemone else primary
  28. unless self.client.user_clients.length == 1
  29. # there's gotta be a more concise way...
  30. if self.client.user_clients[0].equal? self
  31. self.client.user_clients[1].primary = true
  32. else
  33. self.client.user_clients[0].primary = true
  34. end
  35. end
  36. end
  37. end
  38.  
  39. end
  40.  
  41. class Client < ActiveRecord::Base
  42. has_many :user_clients, :dependent => true
  43. has_many :users, :through => :user_client
  44.  
  45. end
  46.  
  47. class Client < AR::B
  48. has_many :users, :dependent => :destroy
  49. has_one :primary_contact, :class_name => "User",
  50. :conditions => {:primary_contact => true},
  51. :dependent => :destroy
  52. end
  53.  
  54. class User < AR::B
  55. belongs_to :client
  56.  
  57. after_save :ensure_only_primary
  58. before_create :ensure_at_least_one_primary
  59. after_destroy :select_another_primary
  60.  
  61. private
  62. # We always want one primary contact, so find another one when I'm being
  63. # deleted
  64. def select_another_primary
  65. return unless primary_contact?
  66. u = self.client.users.first
  67. u.update_attribute(:primary_contact, true) if u
  68. end
  69.  
  70. def ensure_at_least_one_primary
  71. return if self.client.users.count(:primary_contact).nonzero?
  72. self.primary_contact = true
  73. end
  74.  
  75. # We want only 1 primary contact, so if I am the primary contact, all other
  76. # ones have to be secondary
  77. def ensure_only_primary
  78. return unless primary_contact?
  79. self.client.users.update_all(["primary_contact = ?", false], ["id <> ?", self.id])
  80. end
  81. end
Add Comment
Please, Sign In to add comment