【发布时间】:2017-01-23 21:49:06
【问题描述】:
在我的 RoR 应用程序中,我正在尝试创建一个表单,以便用户可以一次更新多个记录的字段。为此,我一直在关注此 RailsCast 指南http://railscasts.com/episodes/165-edit-multiple?view=asciicast,但这确实向我展示了该怎么做。
我遇到的问题是我有一个 Recipient 模型,并且想用不同的数据一次更新多个记录的字段。例如,在这个 Recipient 模型中,我有 contact_id 和 information 列,我想要做的是允许用户使用一个表单上的 information 列的数据更新记录。
我的edit_multiple.html.erb表格如下:
<h1>Recipient Specific Information</h1>
<table>
<tr>
<th>Contact</th>
<th>Information</th>
</tr>
<%= form_for :recipient, :url => update_multiple_recipients_path, :html => { :method => :put } do |form| %>
<% for recipient in @recipients %>
<tr>
<%= hidden_field_tag "recipient_ids[]", recipient.id %>
<td><% if not recipient.contact_id.blank? %><%= recipient.contact.firstname %><% elsif not recipient.group_id.blank? %><%= recipient.group.name %><% end %></td>
<td><%= form.text_field :information, id: recipient.id %></td>
</tr>
<% end %>
<%= form.submit "Submit" %>
<% end %>
</table>
Recipients_controller:
class RecipientsController < ApplicationController
def edit_multiple
@recipients = Recipient.where(:email_id => params[:id])
end
def update_multiple
@recipients = Recipient.find(params[:recipient_ids])
@recipients.each do |recipient|
recipient.update_attributes(recipient_params)
end
flash[:notice] = "Updated products!"
redirect_to root_path
end
private
def recipient_params
params.require(:recipient).permit(:contact_id, :information)
end
end
Routes.rb:
resources :recipients do
collection do
get :edit_multiple
put :update_multiple
end
end
我的问题是视图上的以下代码显示收件人的联系人姓名和每个收件人的text_field,以便用户可以输入他们想要为每个收件人存储的信息。目前,在更新记录时,会为每条记录保存最后一次在记录显示上为信息参数输入text_field 的数据。应该发生的是,每个记录的输入到text_fields 的数据应该被保存。
我的问题是是否可以通过控制器中的 HTML id 来识别视图上的每个文本字段?这是因为我想知道是否可以更改控制器中的以下代码以识别每个文本字段并将输入的数据存储到相应的收件人行中。
def update_multiple
@recipients = Recipient.find(params[:recipient_ids])
@recipients.each do |recipient|
# is it possible to take the data entered in a specific text field?
recipient.update_attributes(recipient_params)
end
flash[:notice] = "Updated products!"
redirect_to root_path
end
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 controller