Rails 4.x / ruby 2.x
我正在使用复选框选择记录以进行其他处理。我想在使用sort或paginate时使复选框变粘。
<% @documents.each do |document| %>
<tr>
<td><%= check_box_tag "document_ids[]", document.id %></td>
<td><%= document.id %></td>
<td><%= link_to document.document_title, document %></td>
<removed irrelevent code>
<% end %>
<%= paginate @documents %>
Send Checked Documents as an attachment : <%= submit_tag "Next" %>
以下是我的控制器的两个defs。如果用户只选中了复选框,没有排序或分页(kaminari),并单击下一个按钮,则index.multiple def / view将显示已检查的文档。
但是,如果我选中一个框然后尝试排序或转到下一页,我会丢失已检查的框,它们将被取消选中。
def index
#----------------------------------------------------------------
# index is the method for the main documents listing. We need to pass parameters for sorting (sortable in application_helper) and
# kaminari's paginate
#-----------------------------------------------------------------
@documents = Document.all
if params[:direction] && params[:sort] then # missing sort and direction params cause error. This filters for missing and provide a default view
@documents = Document.order(params[:sort] + ' ' + params[:direction]).page params[:page]
else
@documents = Document.order(:id).page params[:page]
end
end
# ------------------------------------------------- index multiple ------------------------------------
def index_multiple
#-------------------------------------------------------------------------
# index multiple is for the page after the index. The user has checked checkboxes and those
# items will be displayed.
# ---------------------------------------------------------------------------------
$doc_ids = params[:document_ids] # get the parameters from the checkboxes. send_message converted the params to integers
if params[:document_ids] then
@documents = Document.find(params[:document_ids])
else
redirect_to documents_path, :notice => "**************** You must select at least one item **************"
end
end
使复选框变粘的最佳方法是什么?
答案 0 :(得分:0)
根据rails docs,您可以使用第三个参数将复选框设置为选中/取消选中:http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-check_box_tag
将您的代码修改为以下内容并查看其是否有效:
<%= check_box_tag "document_ids[]", document.id, params[:document_ids].include?(document.id) %>