Params传递不从可排序嵌套表单保存

时间:2012-02-06 09:55:09

标签: jquery ruby-on-rails

所以我使用jquerys sortable来排序嵌套表单字段。这是它在分类时提交的控制器方法:

def sort_questions
  params[:questions_attributes].to_a.each_with_index do |id, index|
    question = Question.find(id)
    question.position = index + 1
    question.save(:validate => false)
  end
  render :nothing => true
end

这是通过在Chrome中查看我的检查器来传递的参数:

 "questions_attributes"=>{"1"=>{"content"=>"Where did you grow up?", "position"=>"", "_destroy"=>"false", "id"=>"2"}, "0"=>{"content"=>"What are you doing?", "position"=>"", "_destroy"=>"false", "id"=>"3"}}

这是被调用的jquery可排序函数:

  $('#questions').sortable({
    items:'.fields',
    placeholdet: true,
    axis:'y',
    update: function() {
      $.post("/templates/#{@template.id}/sort_questions?_method=post&" + $('.edit_template').serialize());
    }
  });

位置属性未保存。我一遍又一遍地尝试了sort_questions方法的各种变体而没有运气。

任何帮助都会很棒。谢谢!

这是完整的参数:

"template"=>{"name"=>"Long Term Volunteer Opportunity", "description"=>"This template will be for opportunities that are for long term missionaries.", "default"=>"1", "questions_attributes"=>{"0"=>{"content"=>"What are you doing?", "position"=>"", "_destroy"=>"false", "id"=>"3"}, "1"=>{"content"=>"Where did you grow up?", "position"=>"", "_destroy"=>"false", "id"=>"2"}}}

2 个答案:

答案 0 :(得分:0)

尝试:

 params[:template][:questions_attributes]

答案 1 :(得分:0)

可能必须对此有所了解,我发现了一些潜在的问题:

def sort_questions
  params[:questions_attributes].to_a.each_with_index do |id, index|
    question = Question.find(id)
    question.position = index + 1
    question.save(:validate => false)
  end
  render :nothing => true
end

如@nodrog所述,它应该是params[:template][:questions_attributes]。目前params[:questions_attributes]返回nilnil.to_a[],因此循环永远不会执行。一旦完成,循环中的id将类似于:

[["0",{"content"=>"What are you doing?",...}], ... ]

将其传递给find将无效。您可以使用鲜为人知的语法,如:

params[:template][:questions_attributes].to_a.each_with_index do |(id, attrs), index|
  question = Question.find(id)
  question.position = index + 1
  question.save(:validate => false)
end

接下来,1.9 中的哈希已排序,但我不会指望从表单元素到params哈希的往返,包括解码,要按照与你的相同方式进行排序页面(因此允许each_with_index策略)。您需要使用查询参数中的"position"属性,该参数当前为空。我确信有一百万种方法可以排序和填充该字段,谷歌可能会有很多关于如何做到这一点的信息。

因此,您的最终功能应该类似于:

params[:template][:questions_attributes].to_a.each_with_index do |(id, attrs), index|
  question = Question.find(id)
  question.position = attrs['position']
  question.save # the less validations you skip the better in the long run.
end