I’m working on a food program. The user defines foods, enters their
calories, etc. Then the user goes into a day view with defines a meal
by selected the foods from a drop down list.
So I have a foods controller, a meals controller.
I have the meals model defined with has_many :foods
And I have the foods controller defined with belongs_to :meal
But when I’m not sure when I create the form for it:
I assume you meant meals has_many :foods and food belongs_to :meal in
the models…
What you need is some type of relation table inbetween those two, since
an individual food could appear in any number of meals, could it not?
A simple has_and_belongs_to_many relationship would require a
foods_meals table like:
def self.up
create_table :foods_meals, :id => false do
t.column :food_id, :integer
t.column :meal_id, :integer
end
end
with a has_and_belongs_to_many :foods in the meal model, and the
converse in the food model. Check the rails wiki for examples of HABTM
usage.
Another alternative is a full join table, I dunno, like ‘servings’.
def self.up
create_table :servings do
t.column :food_id, :integer
t.column :meal_id, :integer
* whatever other columns you’d like to track, ounces (aren’t all
those calories per serving size?)
end
end
You will probably need some a prototype helper like observe_field to
see what you selected in terms of a meal and update the options for
the foods selection.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.