Skip to content

Instantly share code, notes, and snippets.

@derekrockwell
Last active December 20, 2015 18:59
Show Gist options
  • Save derekrockwell/6179769 to your computer and use it in GitHub Desktop.
Save derekrockwell/6179769 to your computer and use it in GitHub Desktop.
has and belongs to many magic
class User < ActiveRecord::Base
#magically looks up repertoires with user_id = this user's id
has_many :repertoires
end
class Repertoire < ActiveRecord::Base
#songly data and methods
#requires user_id integer on repertoire table
belongs_to :user
end
#add repertoire to user
user = User.find(x)
user.repertoires << Repertoire.create(params)
#find repertoires
user.repertoires
user.repertoires.find(repertoire_id)
user.repertoires.where(song_name_field_thing: "Gangnam Style")
RepertoiresController < ActionController::Base
def create
repertoire = Repertoire.new(params[:repertoire])
repertoire.user = current_user
repertoire.save
end
def show
#...
end
def update
#...
end
def destroy
#...
end
def edit
#...
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment