How do you populate a collection in a form from a dependent table?

Hi,

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:

New meal

<%= error_messages_for :meal %>

<% form_for(@meal) do |f| %>

Time
<%= f.datetime_select :time %>

Food
<%= f.text_select :food %>

<%= f.submit "Create" %>

<% end %>

<%= link_to ‘Back’, meals_path %>

The issue is I need f.text_select and the options available to the
user to come from the food table. Anybody know how that would look in
code?

Thanks,

Ron

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

then the models would look something like

meal
has_many :servings
has_many :foods, :through => :servings

food
has_many :servings
has_many :meals, :through => :servings

serving
belongs_to :meal
belongs_to :food

At the risk of writing a dissertation on the subject, google for “rails
has_many through” for a plethora of info and how-to’s

You have to rethink your models. At the very least, you need a many to
many relation between foods and meals.

Food
has_and_belongs_to_many :meals

Meals
has_and_belongs_to_many :foods

that will allow you to select the same foods for multiple meals.

for a controller and view for that, you might want to check

http://wiki.rubyonrails.org/rails/pages/CheckboxHABTM

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.

| Privacy Policy | Terms of Service | Remote Ruby Jobs