Ricky
Ricky

Reputation: 2907

Rails 4 - Association between two models

New to Rails here; having trouble grasping how to model a relationship between two models:

The units table simply contains rows for "grams", "cups", "millilitres"

I would like to associate the units table to the foods table. The goal being that if "serving_size" was say 100, then we would know whether it's ounces, grams or millilitres.

I have no idea how to do this

To start:

But I don't know what the proper way to go from here is? I could write methods that do raw SQL commands, but there must be an easier way

Can we accomplish this so that I can do something like: Food.find( name: 'milk' ).unit.name ?

Any help is appreciated!

Thanks!

Upvotes: 0

Views: 189

Answers (1)

hypern
hypern

Reputation: 887

Based on your problem description I would do this differently. I'd run the following commands in the terminal

rails g model Unit name:string
rails g model Food name:string service_size:integer calories:integer unit:references 

Rails will magically infer everything else.

That should create the migrations and models with the associations you need to assign a unit to a food. The interesting thing about this association that gets generated is that a food 'belongs_to' a unit and a unit 'has_many' foods. I did it this way so that many food records can share the same unit, rather than redundantly assigning the same unit through a new record for every food you create.

EDIT: If you want to access all food associated with a unit then you should add has_many :foods to the unit model.

Upvotes: 2

Related Questions