2012-02-06 62 views
0

因此,我使用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"}}} 

回答

0

可能需要以這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]返回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 
+0

查看我在帖子末尾添加的更改。現在它工作正常。謝謝! – Marc 2012-02-07 00:03:12

0

嘗試:

params[:template][:questions_attributes] 
+0

已經嘗試過......不dice.But這就是爲什麼我'''question.save(:驗證=>假)'''所以它會跳過驗證。 – Marc 2012-02-06 10:17:50

+0

你可以顯示你的完整參數 – nodrog 2012-02-06 15:11:30

+0

修改了答案 – nodrog 2012-02-06 15:18:54