Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>My solution is to do everything in the join model. I think this works correctly on the client transitions to or from zero associations, always guaranteeing a primary contact is designated if there is any existing association. I'd be interested to hear anyone's feedback.</p> <hr> <p>I'm new here, so cannot comment on François below. I can only edit my own entry. His solution presumes user to client is one to many, whereas my solution presumes many to many. I was thinking the user model represented an "agent" or "rep" perhaps, and would surely manage multiple clients. The question is ambiguous in this regard.</p> <hr> <pre><code>class User &lt; ActiveRecord::Base has_many :user_clients, :dependent =&gt; true has_many :clients, :through =&gt; :user_client end class UserClient &lt; 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 &lt; ActiveRecord::Base has_many :user_clients, :dependent =&gt; true has_many :users, :through =&gt; :user_client end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload