DRing DRing - 3 months ago 6x
MySQL Question

Substituting Reference id in one table for field in another

Im new to Rails and having trouble setting up the relationship to work with a simple reference ID. I have a table for Recipes with a field for course selection that is an integer. That integer refers to a table that is just a reference table for all the different possible courses. How can i set up the relationship so that when I call recipe.course it returns the course name and not the id number


Take a look at has_many and belongs_to relations: http://guides.rubyonrails.org/association_basics.html

The associations you want are:
Recipe belongs_to: :course
Course has_many: :recipes

Then be sure to generate a migration to add course_id to Recipe. (Remember this with Rails: Convention over Configuration. The convention is to use model_id as the association column name.)

With both of these associations set and the database migrated correctly, recipe.course will return the instance of Course matching recipe.course_id. (You can then simply do recipe.course.name to get the Course name.)

You will also incedentally be able to do course.recipes and get the relation of all Recipes associated to that Course.