Skip to content

Instantly share code, notes, and snippets.

@mrnugget
Created January 3, 2012 13:37
Show Gist options
  • Save mrnugget/1554910 to your computer and use it in GitHub Desktop.
Save mrnugget/1554910 to your computer and use it in GitHub Desktop.
Songs and Tags
# Models
class Song < ActiveRecord::Base
has_many :song_tags
has_many :tags, :through => :song_tags
end
class SongTag < ActiveRecord::Base
belongs_to :song
belongs_to :tag
end
class Tag < ActiveRecord::Base
has_many :song_tags
has_many :songs, :through => :song_tags
end
# Migrations
class CreateSongs < ActiveRecord::Migration
def change
create_table :songs do |t|
t.string :name
t.string :genre
t.timestamps
end
end
end
class CreateTags < ActiveRecord::Migration
def change
create_table :tags do |t|
t.string :name
t.timestamps
end
end
end
class CreateSongTags < ActiveRecord::Migration
def change
create_table :song_tags do |t|
t.integer :song_id
t.integer :tag_id
t.timestamps
end
end
end
# Usage
1.9.2-p290 :001 > song = Song.create(name: "Let them bitches dance (remix)")
SQL (61.4ms) INSERT INTO "songs" ("created_at", "genre", "name", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Tue, 03 Jan 2012 13:37:12 UTC +00:00], ["genre", nil], ["name", "Let them bitches dance (remix)"], ["updated_at", Tue, 03 Jan 2012 13:37:12 UTC +00:00]]
=> #<Song id: 8, name: "Let them bitches dance (remix)", genre: nil, created_at: "2012-01-03 13:37:12", updated_at: "2012-01-03 13:37:12">
1.9.2-p290 :002 > tag = Tag.create(name: "Awesum!!!")
SQL (2.3ms) INSERT INTO "tags" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", Tue, 03 Jan 2012 13:37:24 UTC +00:00], ["name", "Awesum!!!"], ["updated_at", Tue, 03 Jan 2012 13:37:24 UTC +00:00]]
=> #<Tag id: 11, name: "Awesum!!!", created_at: "2012-01-03 13:37:24", updated_at: "2012-01-03 13:37:24">
1.9.2-p290 :003 > song.song_tags.create(:tag_id => tag.id)
SQL (1.6ms) INSERT INTO "song_tags" ("created_at", "song_id", "tag_id", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Tue, 03 Jan 2012 13:37:36 UTC +00:00], ["song_id", 8], ["tag_id", 11], ["updated_at", Tue, 03 Jan 2012 13:37:36 UTC +00:00]]
=> #<SongTag id: 9, song_id: 8, tag_id: 11, created_at: "2012-01-03 13:37:36", updated_at: "2012-01-03 13:37:36">
1.9.2-p290 :004 > song.tags.all
Tag Load (0.7ms) SELECT "tags".* FROM "tags" INNER JOIN "song_tags" ON "tags"."id" = "song_tags"."tag_id" WHERE "song_tags"."song_id" = 8
=> [#<Tag id: 11, name: "Awesum!!!", created_at: "2012-01-03 13:37:24", updated_at: "2012-01-03 13:37:24">]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment