0

I am new to rails and have a very basic question.

While creating models, for ex. I have to store recipe and its steps. Now should i make recipe table, steps table and recipe_steps table or should i have recipe , steps table and in the model for recipe define has_many :steps?

Any help would be great.

Thanks a lot

abhilash
  • 1,587
  • 2
  • 10
  • 17

1 Answers1

0

You always need to have 3 tables in your database. As you said recipes steps and recipe_steps

Then you have two solutions with your models. The first one with 3 models:

class Recipe
  has_many :recipe_steps
  has_many :steps, through: :recipe_steps
end

class Step
  has_many :recipe_steps
  has_many :recipes, through: :recipe_steps
end

class RecipeStep
  belongs_to :step
  belongs_to :recipe
end

The second one with only two models:

class Recipe
  has_and_belongs_to_many :steps
end

class Step
  has_and_belongs_to_many :recipes
end

You will use the second solution if you don't want to manage data in the recipe_steps table. But if you want to add some informations in this table (price or quantity for example), you must use the first solution.

In all cases you must create the 3 tables.

You will find more information here: http://guides.rubyonrails.org/association_basics.html

I hope this help

CupraR_On_Rails
  • 2,449
  • 1
  • 19
  • 24
  • Thanks Cupra: That was helpful. Though i think i need to clarify, each recipe has multiple steps, basically a one to many relation. In this case too, do we need 3 tables? – abhilash Feb 05 '13 at 12:11
  • For one to many relation you don't need 3 tables. You will have 2 tables with a `belongs_to` for the model which have one relation and `has_many` for the other model. You will find more informations here: http://guides.rubyonrails.org/association_basics.html – CupraR_On_Rails Feb 05 '13 at 12:38
  • Yup thanks Cupra. Appreciate the help. I am doing exactly as you suggested, wanted to be sure of what i am doing. Thanks again. – abhilash Feb 05 '13 at 12:55