Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are two "railsier" ways I can think of to solve this.</p> <p><strong>First Way:</strong> Why not just make these methods?</p> <p>In the first example you gave, try this in your Business class:</p> <pre><code>def physical_address self.address.where(:category =&gt; 'physical').first end </code></pre> <p>Now calling <code>business.physical_address</code> would return the address object. In the same way you can do this with your HABTM association.</p> <pre><code>class A &lt; ActiveRecord::Base ... def type_1 self.bs.where(:category=&gt;'type_1').first end ... end </code></pre> <p>Now calling <code>a.type_1</code> would return the single B having a category of 'Type_1' (or the first if there were more than one).</p> <p><strong>Second Way:</strong> More useful if you thought there would ever be more than one match for a given 'virtual relationship', you could just make these conditions a scope. So, for the second example:</p> <pre><code>class B &lt; ActiveRecord::Base ... scope :type_1 { where(:category=&gt;'type_1') } ... end </code></pre> <p>Now if you called <code>a.bs.type_1.first</code> you'd get the B you were looking for. You could also put <code>.first</code> in the scope if you will never have more than one.</p> <p>To enforce there being only one you can also create a <a href="http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_uniqueness_of" rel="nofollow">uniqueness validation</a>, validating uniqueness of a category with a given parent object.</p> <p>Using either of these options seems to me to be much closer to the "Rails Way" of solving your problem than building these "virtual" relationships is. Maybe it's just me though.</p> <p>Please try this and let me know if you have any trouble :)</p>
 

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