2016-01-05 29 views
0

Rails 4.x/ruby​​ 2.x如何在rails中制作checkbox_tag粘贴?

我正在使用复选框来选择记录以进行其他处理。我想在使用排序或分页时使复选框变得粘滞。

<% @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 

什么是使复选框粘滞的最佳方法是什么? http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-check_box_tag

修改代码以下面看看它的工作原理:

回答

0

根据轨道文档,你可以使用第三个参数设置为复选框选中/取消选中

<%= check_box_tag "document_ids[]", document.id, params[:document_ids].include?(document.id) %>