Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a way you can do it. The basics (before the 70 lines of code) are:</p> <ul> <li>create a has_many for each car type</li> <li>define a method "wheels" that uses the table name in the association to get the right wheels</li> </ul> <p>Let me know if you have any questions</p> <pre><code>#!/usr/bin/env ruby %w|rubygems active_record irb|.each {|lib| require lib} ActiveSupport::Inflector.inflections.singular("toyota", "toyota") CAR_TYPES = %w|ford buick toyota| ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Base.establish_connection( :adapter =&gt; "sqlite3", :database =&gt; ":memory:" ) ActiveRecord::Schema.define do create_table :cars do |t| t.string :name end create_table :car_to_wheel_table_map, :id =&gt; false do |t| t.integer :car_id t.string :wheel_table end CAR_TYPES.each do |car_type| create_table "wheels_for_#{car_type.pluralize}" do |t| t.integer :car_id t.string :color end end end CAR_TYPES.each do |car_type| eval &lt;&lt;-END class #{car_type.classify}Wheel &lt; ActiveRecord::Base set_table_name "wheels_for_#{car_type.pluralize}" belongs_to :car end END end class Car &lt; ActiveRecord::Base has_one :car_wheel_map CAR_TYPES.each do |car_type| has_many "#{car_type}_wheels" end delegate :wheel_table, :to =&gt; :car_wheel_map def wheels send("#{wheel_table}_wheels") end end class CarWheelMap &lt; ActiveRecord::Base set_table_name "car_to_wheel_table_map" belongs_to :car end rav4 = Car.create(:name =&gt; "Rav4") rav4.create_car_wheel_map(:wheel_table =&gt; "toyota") rav4.wheels.create(:color =&gt; "red") fiesta = Car.create(:name =&gt; "Fiesta") fiesta.create_car_wheel_map(:wheel_table =&gt; "ford") fiesta.wheels.create(:color =&gt; "green") IRB.start if __FILE__ == $0 </code></pre>
 

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