Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing many-to-many nested models in Rails
    primarykey
    data
    text
    <p>I've got the following situation setup to model a Customer with multiple addresses and a reference table for the type of address. The data model is Customer - Address : many to many relationship, represented with a join table called 'Location'.<br> LocationType - Location : one to many, so that a locationtype (eg 'work', 'home') can have many associations to a Location.</p> <p>What i'm trying to achieve is the ability to simply locate all the 'work' addresses for a customer, or the 'delivery' addresses. Whilst avoiding having the text duplicated in the join table Location</p> <p>The model(s) look like:</p> <pre><code>class Address &lt; ActiveRecord::Base has_many :locations has_many :customers, :through =&gt; :locations end class Customer &lt; ActiveRecord::Base has_many :locations has_many :addresses, :through =&gt; :locations do def special_location(loc) find :all, :conditions =&gt; ['addr_type == ?', loc] end end end class Location &lt; ActiveRecord::Base belongs_to :address belongs_to :customer belongs_to :locationtype end class LocationType &lt; ActiveRecord::Base has_many :locations end </code></pre> <p>This works ok for the simple cases of : </p> <pre><code>@customer = Customer.find(1) @customer.addresses # return all addresses </code></pre> <p>And with the 'special helper method' of special_location("string") I can achieve the result. What I wanted to find out is how I could achieve the same via the use of the additional reference table (LocationType)<br> Something along the lines of </p> <pre><code>@customer.addresses.find_locationtype("work") </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.
 

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