Form to create multiple models


#1

Hi

I’m a RoR beginner so excuse any potential stupid questions.

I have 3 models in an attempt to model the following

  1. I have a Dayworkout which is a workout for one days workout (day of
    the week independent)
  2. Weekworkout is a collection of Dayworkouts, one per day
  3. Dateworkout is a separate model just to link a Dayworkout with a
    Weekworkout but including the day-of-the-week info. (ie
    Monday=workout1,Tuesday=workout2,Wednesday=workout1 etc…)

This is following what I think is the recommended approach, ie creating
a separate model just to link the two other models?

Here are the declarations

Weekwork

class Weekworkout < ActiveRecord::Base
has_many :dateworkouts
end
class CreateWeekworkouts < ActiveRecord::Migration
def self.up
create_table :weekworkouts do |t|
t.string :name
end
end

Dayworkout

class Dayworkout < ActiveRecord::Base
has_many :dateworkouts
end
class CreateDayworkouts < ActiveRecord::Migration
def self.up
create_table :dayworkouts do |t|
t.string :name
end
end
end

#Dateworkout
class Dateworkout < ActiveRecord::Base
belongs_to :dayworkout
belongs_to :weekworkout
end
class CreateDateworkouts < ActiveRecord::Migration
def self.up
create_table :dateworkouts do |t|
t.integer :dayworkout_id
t.integer :weekworkout_id
t.string :dayofweek
end
end
end

I think this is ok but my confusion starts when I try to create form to
create a new weekworkout. My controller is working ok, presenting the
correct data to the view but in the view I have my problems

Controller

def new
@weekworkout = Weekworkout.new
@coach = current_user.coach
# present all the workouts this coach has defined to the view
@dayworkouts = @coach.find_workouts
# all the days of the week
@daysofweek = %w{Monday Tuesday Wednesday Thursday Friday Saturday
Sunday}

respond_to do |format|
  format.html # new.html.erb
  format.xml  { render :xml => @weekworkout }
end

end

view

<% form_for(@weekworkout) do |f| %>
<%= f.error_messages %>

<%= f.label :name %>
<%= f.text_field :name %>

<% @daysofweek.each do |day|%>

<%= f.label day %> <%= f.collection_select(:dateworkouts, @dayworkouts, :id, :name )%>

<% end %>

<%= f.submit "Create" %>

<% end %>

Basically I don’t know what to put in the collection_select arguments to
return the data to the controller.
When I finish I want the following

  1. Have created a Weekworkout with a name and 7 dateworkouts
  2. Have created 7 dateworkouts with a day of the week, the id of the
    Weekworkout and the id of the dayworkout.

If anything isn’t clear let me know and I will try and clarify.

Any ideas?

D