Friday, September 16, 2011

On the other other hand

I like using polymorphic tables in Rails, it's often a very nice way of structuring access to a single object from multiple points.

To define a polymorphic association, you need to to this in your class:

class Thing < ActiveRecord::Base
   belongs_to :thingable, :polymorphic => true
   #...
end

and on the other side

class Foo < ActiveRecord::Base
   has_may :things :as => :thingable
end

class Bar < ActiveRecord::Base
   has_may :things :as => :thingable
end

Your migration looks like:

class CreateThings < ActiveRecord::Migration
  def change
    create_table :things do |t|
      # attributes ...
      t.string :thingable_type
      #turns into thingable_id
      t.belongs_to :thingable
      t.timestamps
    end
  end
end

Enter the hand that is short

class CreateThings < ActiveRecord::Migration
  def change
    create_table :things do |t|
      # attributes ...
      t.references :thingable, :polymorphic => true
      t.timestamps
    end
  end
end

No comments:

Post a Comment