Rails fields_for验证后现有记录的重复表单

时间:2011-06-16 02:57:24

标签: ruby-on-rails ruby-on-rails-3 nested-forms nested-attributes fields-for

我遇到了一个相当奇怪的错误。我有一个嵌套的表单,按预期工作,除非在现有记录上验证失败。当现有记录上的验证失败时,重新呈现的编辑视图包含两次无效记录的字段。根据对象当前存储的方式填写第一组字段。第二组字段填写了刚刚提交并发现无效的信息。

我有一个基本的嵌套表单,其中父(ShiftPeriod)has_many children(Shifts),每个孩子都属于父。 ShiftPeriod接受移位的accept_nested_attributes,其中allow_destroy设置为true。我正在使用nested_form gem,但我也尝试使用具有相同结果的常规form_for

ShiftPeriod的形式(我尽可能地删除以试图保持简单直到我弄明白):

<%= nested_form_for @shift_period do |f| %>
  <%= f.fields_for :shifts %>
  <%= f.link_to_add "Add shift", :shifts %>
  <%= f.submit %>
<% end %>

带有班次字段的部分:

<%= f.select :member_id, options_for_select(Member.crew_members.order('last_name').collect{|member| ["#{member.last_name}, #{member.first_name}", member.id]}, :selected => Member.where(:bars_num == 1).first.id) %>
<%= f.collection_select :start_time, @time_range, :dup, :hour, :selected => Time.parse(f.object.start_time.to_s) || @shift_period.start_time %>
<%= f.collection_select :end_time, @time_range, :dup, :hour, :selected => f.object.new_record? ? @time_range.last : Time.parse(f.object.end_time.to_s) %>
<%= f.select :repeat_month, options_for_select([['Never', false], ['Monthly', true]]) %>
<%= f.select :repeat, options_for_select([['Never', 0], ['Every Other Week', 1], ['Every Week', 2]]) %>
<%= f.link_to_remove "Remove" %>

Shift对象的相关部分:

class Shift < ActiveRecord::Base
  include Coverage::SetOperations

  belongs_to :member
  belongs_to :shift_period

  delegate :date, :to => :shift_period
  delegate :daynight, :to => :shift_period

  after_save :update_shift_period_open_slots
  after_destroy :update_shift_period_open_slots

  validates_presence_of :member, :start_time, :end_time, :shift_period

ShiftPeriod对象的相关部分:

class ShiftPeriod < ActiveRecord::Base
  has_many :shifts
  has_many :open_slots, :dependent => :destroy
  has_many :calls
  after_create :update_open_slots
  validates_presence_of :date
  validates :date, :uniqueness => {:scope => :daynight}

  accepts_nested_attributes_for :shifts, :reject_if => lambda {|a| a[:start_time].blank? || a[:end_time].blank? || a[:member_id].blank? || a[:repeat].blank? }, :allow_destroy => true

控制器: as_many children(Shifts)和每个孩子属于父母。 ShiftPeriod接受移位的accept_nested_attributes,其中allow_destroy设置为true。我正在使用nested_form gem,但我也尝试使用具有相同结果的常规form_for

控制器:

def edit
  @shift_period = ShiftPeriod.find(params[:id])
  set_time_range
end

def set_time_range
  @time_range = @shift_period.daynight ? (6..18).to_a : (18..23).to_a + (0..6).to_a
  @time_range.collect!{|val| @shift_period.start_time - @shift_period.start_time.hour.hours + val.hours }
end

def update
  @shift_period = ShiftPeriod.find(params[:id])
  respond_to do |format|
    if @shift_period.update_attributes(params[:shift_period])
      format.html { redirect_to(schedule_path(:date => @shift_period.date, :notice => 'Shift period was successfully updated')) }
      format.xml  { head :ok }
    else
      set_time_range
      format.html { render :action => "edit" }
      format.xml  { render :xml => @shift_period.errors, :status => :unprocessable_entity }
    end
  end
end

ShiftPeriod的形式(我尽可能地删除以试图保持简单直到我弄明白):

<%= nested_form_for @shift_period do |f| %>
  <%= f.fields_for :shifts %>
  <%= f.link_to_add "Add shift", :shifts %>
  <%= f.submit %>
<% end %>

带有班次字段的部分:

<%= f.select :member_id, options_for_select(Member.crew_members.order('last_name').collect{|member| ["#{member.last_name}, #{member.first_name}", member.id]}, :selected => Member.where(:bars_num == 1).first.id) %>
<%= f.collection_select :start_time, @time_range, :dup, :hour, :selected => Time.parse(f.object.start_time.to_s) || @shift_period.start_time %>
<%= f.collection_select :end_time, @time_range, :dup, :hour, :selected => f.object.new_record? ? @time_range.last : Time.parse(f.object.end_time.to_s) %>
<%= f.select :repeat_month, options_for_select([['Never', false], ['Monthly', true]]) %>
<%= f.select :repeat, options_for_select([['Never', 0], ['Every Other Week', 1], ['Every Week', 2]]) %>
<%= f.link_to_remove "Remove" %>

Shift对象的相关部分:

class Shift < ActiveRecord::Base
  include Coverage::SetOperations

  belongs_to :member
  belongs_to :shift_period

  delegate :date, :to => :shift_period
  delegate :daynight, :to => :shift_period

  after_save :update_shift_period_open_slots
  after_destroy :update_shift_period_open_slots

  validates_presence_of :member, :start_time, :end_time, :shift_period

ShiftPeriod对象的相关部分:

class ShiftPeriod < ActiveRecord::Base
  has_many :shifts
  has_many :open_slots, :dependent => :destroy
  has_many :calls
  after_create :update_open_slots
  validates_presence_of :date
  validates :date, :uniqueness => {:scope => :daynight}

  accepts_nested_attributes_for :shifts, :reject_if => lambda {|a| a[:start_time].blank? || a[:end_time].blank? || a[:member_id].blank? || a[:repeat].blank? }, :allow_destroy => true

控制器:

def edit
  @shift_period = ShiftPeriod.find(params[:id])
  set_time_range
end

def set_time_range
  @time_range = @shift_period.daynight ? (6..18).to_a : (18..23).to_a + (0..6).to_a
  @time_range.collect!{|val| @shift_period.start_time - @shift_period.start_time.hour.hours + val.hours }
end

def update
  @shift_period = ShiftPeriod.find(params[:id])
  respond_to do |format|
    if @shift_period.update_attributes(params[:shift_period])
      format.html { redirect_to(schedule_path(:date => @shift_period.date, :notice => 'Shift period was successfully updated')) }
      format.xml  { head :ok }
    else
      set_time_range
      format.html { render :action => "edit" }
      format.xml  { render :xml => @shift_period.errors, :status => :unprocessable_entity }
    end
  end
end

1 个答案:

答案 0 :(得分:1)

以下是我现在用来解决这个问题的黑客,非常感谢更好的想法。

def update
  @shift_period = ShiftPeriod.find(params[:id])
  if @shift_period.update_attributes(params[:shift_period])
    redirect_to(schedule_path(:date => @shift_period.date, :notice => 'Shift period was successfully updated')) 
  else
    set_time_range

    new_records = []
    @shift_period.shifts.each{|shift| if shift.new_record? then new_records << shift end}
    @shift_period.shifts.slice!(0,@shift_period.shifts.length/2)
    @shift_period.shifts += new_records
    render :action => "edit"
  end