rails 5 form_tag具有原始DB值,并且在表单中进行新选择后,必须更新两个记录

我有一个带有radio_button_tag的form_tag,它填充了来自DB的数据。 它必须简单地定向到自定义更新操作(update_multiple),其中为表单中已更改的所有2条记录更新布尔列。

例如,当最初从DB填充表单并选择记录1的单选按钮时,现在用户将其选择更改为记录3,然后在提交表单标记时必须更新两个记录,但问题是提交时的代码,仅收集现在在该组中选择的记录的ID。如何获取该记录的id也未被选中,以便我可以一次性更新两个这些记录?

如果提交无法处理此操作,那么控制器或表单中是否有一种方法可以在填充表单之前保留初始选定记录的ID? 如您所见,我尝试使用radio_button_tag收集一组ids []。

TIA的帮助。

这是表单代码:

    params[:main] %> 
Select a CV Resume Name

'button' %>

这是控制器update_multiple代码。

 def update_multiple CvAttachment.update_all(["updated_at=?", Time.now], :id => params[:cv_attachment_ids]) 

结束

我可以想出两种方法来实现你的目标。

  1. 将属于该用户的所有附件的布尔值更新为false,然后将已选择的附件更新为true
  2. 在表单中包含一个隐藏字段,并将其设置为已经为true的id。 然后在控制器操作中,将选中的一个更新为true,将隐藏字段中的一个更新为false。 这可能是一个更好的选择,您可能希望在事务中包装d / b更新。

      <% @cv_attachments.each do |cv_attachment| %> <% if cv_attachment.main %> <%= hidden_field_tag "ex_main_cv", cv_attachment.id %> <% end %>  <%= radio_button_tag "main_cv", cv_attachment.id, cv_attachment.main %>  <%= cv_attachment.attachment.file.basename %>  <% end %>  

调节器

 def update_main_attachment // probably a better name for this method if params["ex_main_cv"] != params["main_cv"] Attachment.transaction do deselected_attachment = Attachment.find(params["ex_main_cv"] deselected_attachment.update_attribute(:main, false) selected_attachment = Attachment.find(params["main_cv"] selected_attachment.update_attribute(:main, true) end end end 

非常感谢@margo。 在这里’我如何解决它部分使用hidden_​​field的方式。 但是现在保持这个线程打开,因为我正在为同一列的切换进行2次DB更新。

  <% @cv_attachments.each do |cv_attachment| %> <% if cv_attachment.main %> <%= hidden_field_tag "ex_main", cv_attachment.id %> <% end %>  <%= radio_button_tag "new_main", cv_attachment.id, cv_attachment.main, :id => "#{cv_attachment.id}"%>  <%= cv_attachment.attachment.file.basename %>  <% end %>  

并在控制器中:

 def update_main if request.put? if params["ex_main"] != params["new_main"] CvAttachment.find(params[:ex_main]).toggle!(:main) CvAttachment.find(params[:new_main]).toggle!(:main) end end