Take the 2-minute tour ×

I have a "accepts_nested_attributes_for" relationship between "timesheet" and "timesheetlines". This works great when editing (edit/update) a timesheet, but when adding a new timesheet (new/create), it returns the following error:

tms timesheetlines tms timesheet can't be empty

It seems it doesn't know to which timesheet the new timesheetlines belong. This is the relationship in timesheet:

has_many :tms_timesheetlines, :dependent => :destroy, :order=>"daynr ASC"
accepts_nested_attributes_for :tms_timesheetlines, :reject_if => lambda { |a| a[:daynr].blank? }, :allow_destroy => true

And in the "new" action the timesheetlines are build:

@timesheet = TmsTimesheet.new
month_lines = Time.days_in_month(@current_period.period_nr).to_i
month_lines.times { @timesheet.tms_timesheetlines.build }

Any ideas why it works without any problem when editing, but not when creating? Thanks!


Both saving a new and edited timesheet works when I add this hidden field with each timesheetline when it is a new timesheet:

<%= tl.hidden_field :tms_timesheet_id, :value => timesheet %>

And this when it is an edit:

<%= tl.hidden_field :tms_timesheet_id, :value => timesheet.id %>

Why the difference to make both work?

share|improve this question
I have updated my question with something that works, but what is still weird in my opinion. –  John Apr 12 '12 at 18:31
add comment

1 Answer

up vote 0 down vote accepted

Check your validation on :tms_timesheetlines. My guess is that it's validating the presence of timesheet and failing on that.

If this is the case, then the reason why it's failing on create but passing on update is because with nested forms, the parent's id will not be known (exist) during validation of the child (timesheetlines) but will exist when you come to update the record.

share|improve this answer
add comment

Your Answer


