Note that there are some explanatory texts on larger screens.

plurals
  1. POhas_one and belongs_to together
    primarykey
    data
    text
    <p>At first glance, this may look like a simple question. You may even suspect it's been answered before, but not <em>quite</em>. I've done a good deal of scouring the web (including stack overflow) and have been unable to find an answer.</p> <p>This is the closest thing I could find: <a href="https://stackoverflow.com/questions/7392434/using-has-one-and-belongs-to-together">Using has_one and belongs_to together</a> however it doesn't quite answer my question.</p> <p>I'm using Rails 4 and MySQL</p> <p>The database structure is as follows:</p> <p>partners table</p> <pre><code>id name primary_contact_id </code></pre> <p>contacts table</p> <pre><code>id partner_id first_name last_name </code></pre> <p>Pretty straight forward, right? Self explanatory.</p> <pre><code>class Partner &lt; ActiveRecord::Base has_one :primary_contact, :class_name =&gt; "Partners::Contact", :primary_key =&gt; 'primary_contact_id' has_many :contacts, :class_name =&gt; "Partners::Contact" accepts_nested_attributes_for :primary_contact validates_presence_of :primary_contact end class Partners::Contact &lt; ActiveRecord::Base belongs_to :partner end </code></pre> <p>As you can see, when creating a partner, a primary contact is required (the forms etc are all set up properly)</p> <p>The only issue I'm experiencing is that when the primary_contact is created along with the partner, ActiveRecord doesn't understand that it needs to assign the partner_id on the contact that is getting created, to the partner_id that is being created...</p> <p>Best practices here? I don't want to create a column in the contacts table that indicates (bool or otherwise) if that contact is primary or not. That's not proper database normalization (regardless of what "rails convention" touts).</p> <p>Thanks for your help and thoughts!</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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