Magic Macros — Has_Many and Self Referential Associations

class Dish 
#name attribute
end
class Ingredient
#name attribute
end
class DishIngredient
#dish_id attribute
#ingredient_id attribute
#quantity attribute
end
class Example 
attr_accessor :name end
end
def name 
@name
end
def name=(param)
@name = param
end
def has_many(method_name, options_hash)   
# Some code here
end

Method Name

Options Hash

  • By Default, Active Record Associations will look for a class model that matches the singular version of our method
  • By Default, Active Record Associations will look for a foriegn_key that matches the current class plus ‘_id’ to the current instance’s id
class Dish 
has_many :dish_ingredients
end
has_many :ingredients, {through: :dish_ingredients}
  1. So first it calls #dish_ingredients
  2. The #dish_ingredients method returns a collection of Instances from the DishIngredient class
  3. Then method then starts iterating over every item in that collection, calling on the #ingredient method to collect an ingredient
  4. It then finishes the method and returns a new collection with just ingredient instances
has_many :dish_ingredients 
has_many :dishs, through: :dish_ingredients end
class Food 
#name attribute
end
class DishIngredient
#dish_id attribute
#ingredient_id attribute
#quantity attribute
end
class Food 
has_many :dish_ingredients, foriegn_key: :dish_id
end
class Food 
has_many :dish_ingredients, foriegn_key: :dish_id
has_many :ingredients, through: :dish_ingredients
end
class DishIngredient
belongs_to :ingredient, class_name: "Food"
end
  1. It first calls the #dish_ingredients method
  2. The #dish_ingredients method returns a collection of Instances from the DishIngredient class
  3. Then method then starts iterating over every item in that collection, it then calls on a method #ingredient in that foreign class to collect a food instance
  4. It then finishes the method and returns a new collection with just food instances that are defined in their relationship to be a ingredient of our food.
class Food 
# A Food item as a dish, can see what ingredients it is made of
has_many :dish_ingredients, foreign_key: :dish_id
has_many :ingredients, through: :dish_ingredients
# A Food item as an ingredient, can see what dishs it is a part
#of
has_many :ingredient_dishs, foreign_key: :ingredient_id, class_name:
has_many :dishs, through: ingredient_dishs
end
class DishIngredient
belongs_to :ingredient, class_name: "Food"
belongs_to :dish, class_name: "Food"
end

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store