如何使用check_box_tag仅选择已检查的记录?

时间:2011-11-04 15:45:38

标签: ruby-on-rails-3 checkbox

伙计我的check_box_tag如下所示

<%= form_tag({:action => 'update_survey_list_status',:projectid=>params[:id], :status=>4}, :id => 'to_be_approved_frm') do %>
  <% @publishedlist.each do |b| %>
    <%= fields_for "beneficiaryloan[#{b.id}]" do |bloan| %>
      <%= bloan.text_field :amount, :class=>'forms_txtbx'%>
      <%= bloan.text_field :rate, :class=>'forms_txtbx'%>
      <%= bloan.text_field :period, :class=>'forms_txtbx'%>
    <% end %> 
    <%= check_box_tag "benificiary_id[#{b.id}]",b.id,:name => "benificiary_id[]"%>
  <% end %>
  <%= submit_tag "Approve", :class=>'form_buttons'  %>
<% end %>

在控制器中,我正在阅读所有这样的受益人ID

params[:beneficiaryloan].each do |key, value|
      beneficiary = Beneficiary.find(key) rescue nil
      @benefciary_loan=beneficiary.beneficiaryloans.build(value)
      @benefciary_loan.beneficiary_id=beneficiary.id
      @benefciary_loan.hfi_id=session[:id].to_s
      @benefciary_loan.status_id=params[:status]
      @benefciary_loan.save if beneficiary
end

我需要的是,将所有受益人ID插入已检查的[beneficiaryloans]表中,但在我的情况下,它会插入所有记录,甚至其中一些记录未经检查。

如何选择仅选中的ID?

1 个答案:

答案 0 :(得分:3)

尝试将check_box_tag更改为

<%= check_box_tag "beneficiaryloan[#{b.id}][enabled]", 1, true %>

然后在您的控制器中执行以下操作:

params[:beneficiaryloan].select{|k,v| v.delete(:enabled).to_i > 0 }.each do |k,v|
  ..
end

由于enabled属性对模型没有影响,您可以将其从生成的beneficiary_load哈希值中删除。