Search code examples
ruby-on-railsmysqliscaffolding

how to deal with Intermediate MySQL tables on Ruby on rails?


I have one table of chefs, one table of restaurants and an intermediate table that relates the restaurants in which a chef has worked

|–––––––––––––––––|  |–––––––––––––––––|  |–––––––––––––––––|
| chef            |  | restaurant      |  | chef_restaurant |
|-----------------|  |-----------------|  |-----------------|
| chef_id         |  | restaurant_id   |  | restaurant_id   |
| name            |  | name            |  | chef_id         |
|_________________|  |_________________|  |_________________|
  1. If I use scaffolding in rails should I generate the scafold for the 3 tables? Does the fact of having intermediate tables in your SQL model is an impair for using scaffolding?
  2. What's your approach to query those intermediate tables?

Solution

  • you need to scaffold chef and restaurant. And for relationship table you don't need models and controls, so just a migration to create relationship table is enough. Two things need to keep in mind were, including habt relationship in chef and restaurant models. And following the naming convention for your relationship table, it must have both table names in plural, in ascending orders. Your relationship table name must be chefs_restaurants

    Rails migration allows to create it easily like below

    rails g migration CreateJoinTable chefs restaurants 
    

    And in your chef model

    has_and_belongs_to_many :restuarants
    

    in your restaurant model

    has_and_belongs_to_many :chefs