Created
April 1, 2015 18:21
-
-
Save alexdunae/c0800bb7d52973e83f45 to your computer and use it in GitHub Desktop.
Raphael habtm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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