Skip to content

Instantly share code, notes, and snippets.

@LNA
Last active January 2, 2016 03:48
Show Gist options
  • Save LNA/8245828 to your computer and use it in GitHub Desktop.
Save LNA/8245828 to your computer and use it in GitHub Desktop.
Association Change.
#First Pass:
module AR
class Guest < ActiveRecord::Base
has_and_belongs_to_many :drinks
end
end
module AR
class Drink < ActiveRecord::Base
has_and_belongs_to_many :guests
end
end
module AR
class Orders < ActiveRecord::Base
#empty
end
end
#Second Pass:
module AR
class Guest < ActiveRecord::Base
has_many :orders, class_name: "Orders"
has_many :drinks, through: :orders, class_name: "Orders"
end
end
module AR
class Drink < ActiveRecord::Base
has_many :orders, class_name: "Orders"
has_many :drinks, through: :orders, class_name: "Orders"
end
end
module AR
class Orders < ActiveRecord::Base
belongs_to :guests, class_name: "Guests"
belongs_to :drinks, class_name: "Drinks"
end
end
# Track how many drinks each guest ordered.
module AR
class Guest < ActiveRecord::Base
has_many :orders, class_name: "Orders"
has_many :drinks, through: :orders, class_name: "Orders"
def drinks
drinks_array = []
AR::Orders.all.each do |relationship|
if relationship.guest_id == self.id
drinks_array << relationship.drink
end
end
drinks_array
end
end
end
# Refactor Code Smells.
module AR
class Guest < ActiveRecord::Base
has_many :ordes, class_name: "Orders"
def drinks
AR::Orders.where("guest_id = ?", self.id).map do |relationship|
relationship.drink
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment