I have a timesheet that has many timesheet items with it. I am able to
insert records to the parent TIMESHEET table and the child
TIMESHEET_ITEMS table. My problem is when I edit the page for an
existing timesheet and the items within it and try to update one of the
item, it creates a new record instead of updating it. Im trying to
figure out what the proper way is to update the attributes of a child
record without creating a new one.
The model is defined as:
class Timesheet < ActiveRecord::Base
has_many :timesheet_items
end
class TimesheetItem < ActiveRecord::Base
belongs_to :timesheet
has_many :timesheet_time_items
end
My controller is:
def update
@timesheet = Timesheet.find(params[:id])
@timesheet.timesheet_items.build(params[:timesheet_item])
if @timesheet.update_attributes(params[:timesheet])
flash[:notice] = ‘Timesheet was successfully updated.’
redirect_to :action => ‘show’, :id => @timesheet
else
render :action => ‘edit’
end
end
My snippet of the jsp page:
<%= start_form_tag :action => ‘update’, :id => @timesheet %>
<%= submit_tag 'Submit Timesheet' %>
<% for timesheet_item in @timesheet.timesheet_items %>
ID: <%= timesheet_item.id %> -
<%= select(“timesheet_item”, “work_category”,
WorkManagementType.find(:all, :conditions => “code_table = ‘CATEGORY’”,
:order => “name DESC”).collect {|workmgmttype| [ workmgmttype.name,
workmgmttype.name ] }, { :selected => timesheet_item.work_category,
:include_blank => true}) %>
<%= select(“timesheet_item”, “work_activity”,
WorkManagementType.find(:all, :conditions => “code_table = ‘ACTIVITY’”,
:order => “name DESC”).collect {|workmgmttype| [ workmgmttype.name,
workmgmttype.name ] }, { :selected => timesheet_item.work_activity,
:include_blank => true }) %>
<% end %>