2009-06-14 24 views
2

我已經大致按照this Railscast的說明設置了一個Rails窗體。如何在多記錄Rails表單中設置複選框的唯一ID?

下面是窗體的代碼:

<% form_tag complete_todos_path, :method => :put do %> 
    <ul> 
    <div id="incomplete_todos"> 
    <% @incomplete_todos.each do |todo| %> 
     <%= render :partial => todo %> 
    <% end %> 
    </div> 
    </ul> 
    <%= submit_tag "Mark as completed" %> 
<% end %> 

而這裏的待辦事項部分代碼:

<div class="todo"> 
    <li> 
     <%= check_box_tag "todo_ids[]", todo.id %> 
     <%=h todo.name %> 
     <%= link_to 'edit', edit_todo_path(todo) %> 
     <%= link_to 'delete', todo, :confirm => 'Are you sure?', :method => :delete %> 
    </li> 
</div> 

它的工作很好,但我期待開始實施AJAX,我需要每個複選框都有一個唯一的ID。現在,生成的輸入標籤看起來像這樣:

<input id="todo_ids_" name="todo_ids[]" type="checkbox" value="7" /> 

每個複選框都有相同的id(「todo_ids_」),這是一個問題。我懷疑這個解決方案很簡單,但我沒有看到它。有小費嗎?

回答

2

我最終使用了與Ryan類似的解決方案,但正如我在評論中寫到的,我必須做出進一步的改變。形式:

<%= check_box_tag "todo_ids[#{todo.id}]", todo.id %> 

在操作由所述形式稱爲:

Todo.update_all(["completed_at = ?", Time.now], :id => params[:todo_ids].keys) 

注意「PARAMS [:todo_ids] .keys」結尾,這是處理奇數一種解決方法路參數格式:

"todo_ids" => {"5"=>"5"} 
1

你可以試試這個,讓我們知道,如果它的工作原理:

check_box_tag "todo_ids[#{todo.id}]", todo.id %> 
+0

生成以下內容: <輸入的ID = 「todo_ids_7」 名稱= 「todo_ids [7]」 類型= 「複選框」 值= 「7」/> 的ID都是唯一的,這是很大的,但它發送在不可思議的方式的參數: todo_ids 「=> {」 5 「=>」 5 「} 我最終使用: Todo.update_all([」 completed_at =「,Time.now?],: id => params [:todo_ids] .keys)作爲一種解決方法,它工作得很好(雖然它看起來像一種凌亂的解決方案)。謝謝! – 2009-06-14 05:31:25

+0

你應該使用params [:todo_ids] .keys.collect(&:to_i) 。 真高興你做到了。 – 2009-06-14 06:12:35

7

<%= check_box_tag "todo_ids[]", todo.id, false, :id => "todo_id_#{todo.id}" -%>或任何你想要的ID是。

我認爲這是一個由check_box_tag造成的錯誤,這個錯誤是由手動給它命名的todo_ids []和調用sanitize_to_id(name)的方法代碼造成的。我昨天遇到了這個,我正在考慮一個補丁。

0

這是預期的行爲,如this comment on a rejected fix explains

您可以使用collection_check_boxes像這樣(HAML語法,不好意思):

# Accumulate todos in a params hash like { todos: { to_complete: [] } } 
= collection_check_boxes(:todos, :to_complete, @incomplete_todos, :id, :name) do |todo_builder| 
    = todo_builder.label do 
    # This is the result of calling :name on the todo, as specified 
    # calling the helper 
    = todo_builder.text 
    = todo_builder.check_box 

當然你也可以使用諧音的塊中,只是通過並使用內部的建設者。

查看API docs的更多選項。

相關問題