所以我使用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"}}}
可能需要稍微了解一下,我看到了几个潜在的问题:
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]
返回nil
,nil.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
策略)。您需要使用查询params中的"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
尝试:
params[:template][:questions_attributes]