如何用Rails Turbo Stream仅替换下拉选框选项而非整个容器?
如何用Rails Turbo Stream仅替换下拉选框的选项内容?
我希望通过Rails Turbo Stream替换下拉选框的选项内容。此前通过JS请求的方式,可在views/projects/filter_units_by_organization.js.erb中编写代码实现替换select#project_unit_id的内容,但使用turbo_stream.erb文件时,Turbo会替换整个div容器,请问能否仅替换select标签的选项?
原JS实现代码
$('select#project_unit_id').html('<%= j options_from_collection_for_select(@filtered_units, :id, :name) %>');
Turbo Stream初始尝试代码
<%= turbo_stream.replace "option" do %> <% end %>
表单代码(views/projects/_form.html.erb)
<div class="field"> <%= f.label :name %><br> <%= f.text_field :name %> </div> <div class="field"> <%= f.label :description %><br> <%= f.text_area :description %> </div> <div class="field"> <%= f.label :organization_id %><br> <%= f.collection_select :organization_id, Organization.all, :id, :name, { prompt: 'Please select' } %> </div> <div class="field"> <%= f.label :unit_id %><br> <%= f.collection_select :unit_id, Unit.all.where(organization_id: :organization_id), :id, :name %> </div> <div class="actions"> <%= f.submit %> </div>
解决方案
基础实现代码
使用turbo_stream.update直接更新目标select标签的内容,而非替换整个容器:
<%= turbo_stream.update "project_unit_id" do options_from_collection_for_select(@objects, :id, :name) %> <% end %>
包含空选项的实现代码
如果需要添加默认的空提示选项,可通过以下方式实现:
<%= turbo_stream.update 'project_unit_id' do %> <%= options_for_select(@objects.collect{ |obj| [obj.name, obj.id] }.unshift(['请选择', nil])) %> <% end %>
内容的提问来源于stack exchange,提问作者Akash Kinwad
相关产品推荐
相关产品推荐

