Alex Frederick Alex Frederick - 5 months ago 10
Ruby Question

How to pluck and display items from another table

I'm building a Yelp type app. I have a table of restaurants, a table of dishes, and a join table between the two that I have named dishings (dish_id & restaurant_id). If a row in dishings exists, that means the restaurant carries that item.

I would like to add a menu to the restaurant show page, which lists out all the menu items associated with that restaurant.

How do I do that?

Answer

In your restaurant model, add this association:

has_and_belongs_to_many :dishes, join_table: :dishings

In your dish model, add this association:

has_and_belongs_to_many :restaurants, join_table: :dishings

Then, to get all dishes for a restaurant: restaurant.dishes

Hope this helps.