accepts_nested_attributes_for适用于编辑/更新,而不是新建/创建



我在"时间表"和"时间表"之间有一个"accepts_nested_attributes_for"关系。这在编辑(编辑/更新)时间表时非常有效,但在添加新时间表(新建/创建)时,它会返回以下错误:

tms timesheetlines tms timesheet can't be empty

它似乎不知道新时间表属于哪个时间表。这是时间表中的关系:

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

在"新"操作中,将生成时间表:

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

有什么想法为什么它在编辑时没有任何问题,但在创建时却没有?谢谢!

更新:

保存新的和编辑的时间表时,当我在每个时间表行中添加此隐藏字段时,当它是新的时间表时,保存它都有效:

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

这是编辑时:

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

为什么差异使两者起作用?

检查您在:tms_timesheetlines上的验证。我的猜测是,它正在验证timesheet的存在并失败。

如果是这种情况,那么它在创建时失败但在传递更新时失败的原因是,对于嵌套表单,父级的 id 在验证子项(时间表)期间不会已知(存在),但在您来更新记录时会存在。

最新更新