Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Serious Ruby ORMs don't do this for a reason: it's inflexible, not explicit enough and too much magic.</p> <p>If you <em>really</em> want this in your project, try coding it yourself in Ruby. Here's what I've done in 5 minutes on top of ActiveRecord:</p> <pre><code>require 'active_record' class ActiveRecord::Base def self.magic! connection.tables.map { |table| klass = Class.new(self) Object.send(:const_set, table.singularize.camelize, klass) }.each { |model| model.column_names.grep(/_id$/).each { |foreign_key| name = foreign_key.sub(/_id$/, '') model.belongs_to(name) name.camelize.constantize.has_many(model.name.tableize) } } end end </code></pre> <p>Let's set up our database tables and have <code>magic!</code> analyze them:</p> <pre><code>ActiveRecord::Base.establish_connection(:adapter =&gt; 'sqlite3', :database =&gt; ':memory:') ActiveRecord::Schema.define do create_table "managers" do |t| t.string "name" end create_table "employees" do |t| t.string "name" t.belongs_to "manager" end end # it happens! ActiveRecord::Base.magic! </code></pre> <p>Create some test records and use it in the way you wanted:</p> <pre><code>mislav = Manager.create :name =&gt; "Mislav" mislav.employees.create(:name =&gt; "Josh") mislav.employees.create(:name =&gt; "Mike") Manager.all.each do |manager| puts manager.name manager.employees.each do |employee| puts employee.name end end </code></pre> <p><a href="http://gist.github.com/255584" rel="nofollow noreferrer">Full code available on this Gist</a>.</p> <p>This only works with <code>belongs_to</code> and <code>has_many</code> associations. If you need a real library that does this and much more, check out <a href="http://magicmodels.rubyforge.org/dr_nic_magic_models/" rel="nofollow noreferrer">Dr Nic's Magic Models</a>.</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