我有一个 simple_form 输入字段,它是表单的一部分,当触发 onchange 事件时,我需要异步更新该输入字段。
我需要更新的字段显示为选择框,因为它是一个集合。但集合代表嵌套集合模型的记录。因此,当用户选择特定值时,我希望能够更新同一字段及其子字段,并让用户可以选择选择任何子字段作为同一字段的值。
问题是,如何只更新该字段而不触及表单的其余部分。
只是为了说明我当前的设置: 表格看起来像这样:
<%= simple_form_for @product, html: {class: 'form-horizontal'} do |f| %>
<%= f.input :product_name %>
<%= f.association :location, collection: @locations, input_html: { data: {remote: :true, url: "/update_locations"} } %>
<%= f.submit 'Post', class: 'btn btn-default btn-lg' %>
<% end %>
@product是一个新产品,属于位置 , @locations 是位置的集合,其中每个has_many 产品 因此使用 simple_form 关联 方法 位置也acts_as_nested_set
我的routes.rb中有这个
get 'update_locations' => 'products#update_locations'
我需要帮助来完成 Controller 操作:
def update_locations
@product = Product.new
@location = Location.find_by_id(params[:product][:location_id])
@locations = @location.children
# TODO: render code that updates the simple_form field with
# the new @locations collection
end
我不确定上面的 Controller 应该呈现的部分 View 中应该包含哪些代码。
最佳答案
问题是我不知道如何只更新 simple_form 中的一个元素。 我对在 Rails 中使用 AJAX 的掌握也很松散,不知道同一个 Controller 可以同时拥有 HTML 和 JS 部分 View ,因此我试图将所有代码都放在 HTML 中,这会很麻烦并且不利于不引人注目JavaScript。
偶然发现 jQuery 方法 ReplaceWith 也非常有帮助。
凭借这些知识,我能够完成我打算做的事情。
我创建了一个 JavaScript 部分 View ,该 View 是为了响应 AJAX 调用而呈现的。该部分呈现一个 .html.erb 部分 View ,该 View 使用更新的元素重建了 simple_form。然后,JS View 从重建的表单中提取更新的元素并使用 jQuery replaceWith()方法仅替换初始表单中的特定元素,同时保持表单的其余部分不变。
这是 JS 部分 (location.js.erb) 的样子:
var updatedLocations = $('#product_location_id', $('<%= j render "updateLocations" %>'))
$('#product_location_id').replaceWith(updatedLocations)
HTML erb 部分 (updateLocations.html.erb) 看起来像这样:
<%= simple_form_for @product, html: {class: 'form-horizontal'} do |f| %>
<%= f.association :location, collection: @locations, input_html: { data: {update_locations: "true", remote: :true, url: "/update_locations"} } %>
<% end %>
Controller :
def update_locations
@product = Product.new
@location = Location.find_by_id(params[:product][:location_id])
@locations = @location.children
if @locations.empty?
render nothing: true
else
render partial: 'locations'
end
end
关于jquery - 如何使用 AJAX 更新 simple_form 输入字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019511/