Skip to content

Instantly share code, notes, and snippets.

@mrandyclark
Created February 27, 2010 20:20
Show Gist options
  • Save mrandyclark/316928 to your computer and use it in GitHub Desktop.
Save mrandyclark/316928 to your computer and use it in GitHub Desktop.
Rails Polymorphic Association migrations and models, check "console.rb" to see end result
# posts migration
# posts are the parent, have many types
class CreatePosts < ActiveRecord::Migration
def self.up
create_table :posts do |t|
t.integer :user_id
t.references :content, :polymorphic => true
t.timestamps
end
end
def self.down
drop_table :posts
end
end
# quotes migration
# quotes are a type of post
class CreateQuotes < ActiveRecord::Migration
def self.up
create_table :quotes do |t|
t.string :text
t.timestamps
end
end
def self.down
drop_table :quotes
end
end
# schedule migration
# schedules are a type of post
class CreateSchedules < ActiveRecord::Migration
def self.up
create_table :schedules do |t|
t.datetime :date
t.string :title
t.string :location
t.string :description
t.timestamps
end
end
def self.down
drop_table :schedules
end
end
# showing how the association works through console
:: script/console
Loading development environment (Rails 2.3.4)
>> p = Post.find(:all)
=> [#<Post id: 1, user_id: 1, featured: true, content_id: 1, content_type: "Quote", created_at: nil, updated_at: nil>, #<Post id: 3, user_id: 1, featured: true, content_id: 1, content_type: "Schedule", created_at: nil, updated_at: nil>]
>> for post in p
>> puts post.display_content
>> end
<h2>This is a quote</h2>
<p>Fort Collins Bumbling Bees<br />Fort Collins High School at 2010-02-25 21:00:00 UTC<br />Description</p>
# post model
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :content, :polymorphic => true
def display_content
return self.content.display_content
end
end
# quotes model
class Quote < ActiveRecord::Base
has_one :post, :as => :content
def display_content
return ["<h2>", self.text, "</h2>"].join('')
end
end
# schedule model
class Schedule < ActiveRecord::Base
has_one :post, :as => :content
def display_content
return [
'<p>', self.title,
'<br />', self.location, " at ", self.date,
'<br />', self.description,
'</p>'
].join('')
end
end
# showing the generated tables
# note "content_type" and "content_id" created from "t.references" in the posts migration
# also, this is auto generated on migration
create_table "posts", :force => true do |t|
t.integer "user_id"
t.boolean "featured"
t.integer "content_id"
t.string "content_type"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "quotes", :force => true do |t|
t.string "text"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "schedules", :force => true do |t|
t.datetime "date"
t.string "title"
t.string "location"
t.string "description"
t.datetime "created_at"
t.datetime "updated_at"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment