javascript - 使用选择刷新 Turbo Frames 而无需在 Rails 7 上提交

标签 javascript ruby-on-rails stimulusjs turbo-frames

我正在学习 Turbo Frames 和 Streams + Stimulus,所以我可能没有 100% 走上正轨。我有一个用于创建新对象的表单,但在表单中我想要一个选择组件,它会根据选择显示某些字段。请务必注意,因此,我不想在用户做出此选择之前提交表单。

这是我的:

_form.html.erb

<div class="form-group mb-3">
   <%= form.label :parking, class: 'form-label' %>
   <%= form.number_field :parking, class: 'form-control' %>
</div>

<%= turbo_frame_tag "turbo_transactions" do %>
   <%= render 'property_transactions' %>
<% end %>

_property_transactions.html.erb

<div class="form-group mb-3" data-controller="property-transaction">
    <%= label_tag :property_transactions, 'Property in:', class: 'form-label' %>
    <%= select_tag :property_transactions, options_for_select(@property_transactions.collect {|p| [p.name, p.id]}), { data: 
    { action: "property-transaction#redraw", property_transaction_target: 'transaction', turbo_frame: 'turbo_transactions' }, 
        class: 'form-control', prompt: '', autocomplete: 'off' } %>
</div>

<% if @property_transaction %>
    <%= turbo_frame_tag @property_transaction.en_translation_key do %>
        <div class="form-group mb-3">
            <%= render @property_transaction.en_translation_key %>
        </div>
    <% end %>
<% end %>

property_transaction_controller.js

import { Controller } from "@hotwired/stimulus";
import Rails from "@rails/ujs";

export default class extends Controller {
    static targets = [ "transaction" ];

    redraw() {
        const params = { property_transaction: this.transaction };
        Rails.ajax({
            type: 'post',
            dataType: 'json',
            url: "/set_property_transaction",
            data: new URLSearchParams(params).toString(),
            success: (response) => { console.log('response', response) }
        });
    }

    get transaction() {
        return this.transactionTarget.value;
    }
}

属性 Controller .rb

def set_property_transaction
    respond_to do |format|
      format.json
      format.turbo_stream do
        if @property_transactions
          @property_transaction = @property_transactions.select { |p| p.id == property_transaction_params }
        else
          @property_transaction = PropertyTransaction.find(property_transaction_params)
        end
      end
    end
  end

set_property_transaction.turbo_stream.erb

<%= turbo_stream.replace @property_transaction.en_translation_key %>

_rent.html.erb

<%= turbo_frame_tag "rent" do %>
    <!-- some input fields -->
<% end %>

_rent_with_option_to_buy.html.erb

<%= turbo_frame_tag "rent-with-option-to-buy" do %>
    <!-- other input fields -->
<% end %>

_sale.html.erb

<%= turbo_frame_tag "sale" do %>
    <!-- more input fields -->
<% end %>

选择选项时,出现这个错误:

Started POST "/set_property_transaction" for ::1 at 2022-09-07 19:49:03 -0600
Processing by PropertiesController#set_property_transaction as JSON
  Parameters: {"property_transaction"=>"2"}
Completed 406 Not Acceptable in 223ms (ActiveRecord: 0.0ms | Allocations: 1879)


  
ActionController::UnknownFormat (PropertiesController#set_property_transaction is missing a template for this request format and variant.

request.formats: ["application/json", "text/javascript", "*/*"]
request.variant: []):

我对此的理解是我缺少 set_property_translation 模板,但我确实有它。不确定我还能做些什么来让它变得可识别。

最佳答案

Les Nightingill 的评论无疑将我引向了正确的方向。我会将所需的更改放在这里。

_property_transactions.html.erb

<div class="form-group mb-3" data-controller="property-transaction">
    <%= label_tag :property_transactions, 'Propiedad en:', class: 'form-label' %>
    <%= select_tag :property_transactions, options_for_select(@property_transactions.collect {|p| [p.name, p.id]}), { data: 
    { action: "property-transaction#redraw", property_transaction_target: 'transaction', turbo_frame: "turbo_transactions" }, 
        class: 'form-control', prompt: '', autocomplete: 'off' } %>
</div>

<%= turbo_frame_tag "dynamic_fields" %>

property_transaction_controller.js

import { Controller } from "@hotwired/stimulus";
import { post } from "@rails/request.js";

export default class extends Controller {
    static targets = [ "transaction" ];

    async redraw() {
        const params = { property_transaction: this.transaction };
        const response = await post("/set_property_transaction", {
            body: params,
            contentType: 'application/json',
            responseKind: 'turbo-stream'
        });
        if (response.ok) {
            console.log('all good', response); // not necessary
        }
    }

    get transaction() {
        return this.transactionTarget.value;
    }
}

set_property_transaction.turbo_stream.erb

<%= turbo_stream.update "dynamic_fields" do %>
  <%= render partial: @property_transaction.en_translation_key %>
<% end %>

关于javascript - 使用选择刷新 Turbo Frames 而无需在 Rails 7 上提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73642924/

相关文章:

javascript - jQuery on click 每隔一段时间就不起作用

javascript - 检测 Javascript 变量是否真的未定义

javascript - link_to 为 :method => :delete routing through GET not DELETE rails 4

ruby-on-rails - ActiveRecord rails : Get records where a field is unique/distinct

JavaScript 即时编译

ruby-on-rails - 当我们必须使用 multipart : true in Rails

jquery - 如何将 Jquery 代码转换为 StimulusJS Controller Rails 7?

javascript - "Page-Specific Javascript"在 rails 上使用 stimulusjs

javascript - 值​stimulus js 无法在 Controller 的单个范围内工作

c# - 如何在回发时将控件 clientID 添加到 Request.Form 集合