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!
Update:
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?
Check your validation on
:tms_timesheetlines. My guess is that it’s validating the presence oftimesheetand 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.