title: Automatically create relationship unless it already exists
body: <pre><code>class Cat &lt; ActiveRecord::Base
      has_many :catbowls
      has_many :bowls, through: :catbowls
  end
  
  class CatBowl &lt; ActiveRecord::Base
      belongs_to :cats
      belongs_to :bowls
  end
  
  class Bowl &lt; ActiveRecord::Base
      has_many :catbowls
      has_many :cats, through: :catbowls
  end
  </code></pre>
  
  <p>In the rails console I can give a bowl to a cat:</p>
  
  <pre><code>cat = Cat.create(name: 'tibbles')
  bowl = Bowl.create(color: 'blue')
  cat.catbowls #=&gt; []
  cat.catbowls.create(bowl_id: bowl.id)
  cat.catbowls #=&gt; [#&lt;Bowl id: 1, color: "blue", created_at: "2014-04-23 22:53:15", updated_at: "2014-04-23 22:53:15"&gt;]
  </code></pre>
  
  <p>This makes sense, and the following association exists:</p>
  
  <pre><code>CatBowl.all #=&gt; [#&lt;Bowl id: 1, cat_id: 1, bowl_id: 1&gt;]
  </code></pre>
  
  <p><strong>However,</strong> here's my problem. If I create the association again, it doesn't actually change the result, but I do get an ineffectual identical catbowl relationship. </p>
  
  <pre><code>cat.catbowls.create(bowl_id: bowl.id)
  cat.catbowls #=&gt; [#&lt;Bowl id: 1, color: "blue", created_at: "2014-04-23 22:53:15", updated_at: "2014-04-23 22:53:15"&gt;]&gt; 
  </code></pre>
  
  <p>This relationship is identical to the previous one and utterly useless: </p>
  
  <pre><code>CatBowl.all #=&gt; [#&lt;Bowl id: 1, cat_id: 1, bowl_id: 1&gt;,#&lt;Bowl id: 2, cat_id: 1, bowl_id: 1&gt;]
  </code></pre>
  
  <p>So how can I stop an existing relationship from being created? What method chain should be used to replace <strong>cat.catbowls.create</strong>, and create a relationship <strong>unless</strong> it already exists?</p>
  
  <p>I could use an unless statement  to do this, </p>
  
  <pre><code>cat.catbowls.create(bowl_id: bowl.id) unless Catbowl.where(cat_id: cat.id, bowl_id:bowl.id).present?
  </code></pre>
  
  <p>however this is pretty cumbersome and results in a lot of queries. What I want to do is so common I'm wondering if some rails magic can help me out?</p>