通过可分类嵌套表格不能保存的参数
问题描述:
因此,我使用jquerys可排序来对嵌套表单域进行排序。这里的控制方法它提交时,它的排序以:通过可分类嵌套表格不能保存的参数
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看着我检查通过PARAMS:
"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方法,没有运气。
任何帮助将是伟大的。谢谢!
下面是完整的PARAMS:
"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"}}}
答
可能需要以这wittle一点,我看到一对夫妇潜在问题:
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
策略)。您需要使用查询参数中的"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
查看我在帖子末尾添加的更改。现在它工作正常。谢谢! – Marc 2012-02-07 00:03:12