使用rails 3以内部forms更新嵌套表单和现有数据

我正在尝试使用嵌套的表单视图来正确更新。 然而,当第二种forms具有现有数据时,这会引起问题。

我正在使用accepts_nested_attributes_for和nested_form_for。 第二个目的是使用js动态添加表单元素。 有关更多信息,请参阅github

我得到的错误是:

Couldn't find Muscle with ID=3685340 for Exercise with ID=212831413 

我试图手动进行更新,但我的代码并没有真正起作用,我的印象是它不应该被需要因为rails假设在引擎盖下处理它。

这个想法是:练习通过目标有很多肌肉,而且在练习forms中,我希望能够增加目标肌肉。

我的模特:

 class Exercise  :destroy has_many :muscles, :through => :targets accepts_nested_attributes_for :muscles, :reject_if => :all_blank ... end class Target  true belongs_to :muscle end class Muscle  :destroy has_many :exercises, :through => :targets end 

我的(haml)观点:

 %p %b Target(s): = f.fields_for :muscles do |e| = e.collection_select :id, Muscle.all, :id, :name = e.link_to_remove "-remove" = f.link_to_add "Add target muscle", :muscles 

最后我失败的控制器:

  def update @exercise = Exercise.find(params[:id]) @exercise.user = current_user params[:exercise][:muscles_attributes].each { |id, muscle| target = Target.where(:exercise_id => @exercise.id , :muscle_id => muscle[:id]).first if target && !(muscle[:_destroy] == "false") puts "!!>>>>>>>>>>>>>>>>>>destroy target #{target.exercise_id} #{target.muscle_id}" target.destroy else if !target t = @exercise.targets.build(:muscle_id => muscle[:id]) t.save end end } respond_to do |format| if @exercise.update_attributes(params[:exercise]) format.html { redirect_to(@exercise, :notice => 'Exercise was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @exercise.errors, :status => :unprocessable_entity } end end end 

请告诉我是否应该公开更多我的代码(无论如何最终结果将是开源),并且非常高兴地推送到github或任何请求,请提前感谢。

你可以通过操纵中间表来实现这一点,这里是targets

插入您的模型:

 accepts_nested_attributes_for :targets 

在你的HTML中,用javascript附加这一行: