4

我有一个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 是属于Location的 新Product@locations是Location的集合,每个都有_many Product 因此使用simple_form关联方法 Location 也作为_as_nested_set

我的 routes.rb 中有这个

get 'update_locations'    => 'products#update_locations'

我需要帮助来完成控制器操作:

  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

我不确定上面的控制器应该呈现的部分视图中应该包含哪些代码。

4

1 回答 1

3

问题是我不知道如何只更新 simple_form 中的一个元素。我对使用带有rails的AJAX也有一个非常松散的把握,不知道你可以同时拥有同一个控制器的HTML和JS部分视图,因此我试图将我的所有代码都放在HTML中,这会很麻烦并且不利于不引人注目JavaScript。

偶然发现 jQuery 方法 replaceWith 也很有帮助。

有了这些知识,我就能够完成我打算做的事情。

我创建了一个响应 AJAX 调用而呈现的 JavaScript 局部视图。部分呈现一个 .html.erb 部分视图,该视图使用更新的元素重建了一个 simple_form。然后,JS 视图从重建的表单中提取更新的元素,并使用 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 %>

和控制器:

  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
于 2015-05-10T23:55:07.353 回答