0

I am having these models in my application:

class Ingredient < ApplicationRecord
  has_many :recipe_ingredients
  has_many :recipes, through: :recipe_ingredients
end

class RecipeIngredient < ApplicationRecord
  belongs_to :recipe
  belongs_to :ingredient
end

class Recipe < ApplicationRecord
  has_many :recipe_ingredients
  has_many :ingredients, through: :recipe_ingredients
end


But Recipe model already has had a text field with same name ingredients, so this setting has_many :ingredients, through: :recipe_ingredients should be changed. How can I change the name ingredients to somethings(ingredient_items) else by using source or as?

Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
Tiktac
  • 966
  • 1
  • 12
  • 32
  • The underlying problem here is defining what the difference between the Ingredient model and the ingredients text field is. What are you storing in the ingredients text field that isn't stored in the Ingredient model? You may then find yourself asking: "Do I need the text field?" to which I imagine the answer is now. After that, you can say: "What is the difference betewen an RecipeIngredient and an Ingredient? Do they need to be two different models? – benjessop Apr 09 '21 at 11:25
  • @benjessop yes you almost right, ingredients text field has its own functionality, so the problem is I should keep as it is. – Tiktac Apr 09 '21 at 13:54
  • Thanks @Eyeslandic, it was easy but my brain is so bad :D – Tiktac Apr 09 '21 at 13:55

2 Answers2

1

using source - you can name the association whatever you want (in your example you mentioned ingredient_items) then specify what source, the source being the association present in the model your current association goes through in you case the model is recipe_ingredients and the association is :ingredient


has_many :ingredient_items, source: :ingredient, through: :recipe_ingredients

Mshka
  • 1,798
  • 1
  • 10
  • 19
1

you can also give this a try:

has_many :items, class_name: "Ingredient"
Alexander
  • 1,072
  • 1
  • 5
  • 9