Skip to content

Instantly share code, notes, and snippets.

@alexdunae
Created April 1, 2015 18:21
Show Gist options
  • Save alexdunae/c0800bb7d52973e83f45 to your computer and use it in GitHub Desktop.
Save alexdunae/c0800bb7d52973e83f45 to your computer and use it in GitHub Desktop.
Raphael habtm
# in a migration
create_table :orders_dishes do |t|
t.belongs_to :order, index: true
t.belongs_to :dish, index: true
end
# in the models
class Order < ActiveRecord::Base
has_and_belongs_to_many :dishes
end
class Dish < ActiveRecord::Base
has_and_belongs_to_many :orders
end
# then you'll be able to do things like this
order = Order.find(111)
milkshake = Dish.find(888)
burger = Dish.find(999)
# we now have a `dishes` association that's like an array
order.dishes << milkshake
order.dishes << burger
order.save!
order.dishes.each do |dish|
puts "Order #{order.id} has dish #{dish.id}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment