ターボフレームを使用してRailsフォームの入力フィールドの値を更新することはできますか?
概要
Rails フォームビルダーでフォームを構築したとします。テキスト フィールドがあり、AJAX とターボ ストリームを使用して入力フィールドの値を動的に更新したいと考えています。
ターボ ストリーム ビューから text_field ヘルパーを使用して、新しく作成されたテキスト フィールドに置き換えずに、同じテキスト フィールドの値を更新することはできますか?
この Gorails チュートリアルにも同様の使用例がありますが、選択タグの値を更新しています。そこで、options_for_select ヘルパーを使用して select タグのオプションを更新し、select フィールドがそのまま DOM 上に残り、オプションのみが置き換えられるようにしました。
解決策
これを行うための組み込みの方法はありませんが、カスタム ターボ ストリーム アクションを作成するのは非常に簡単です。
// app/javascript/application.js
Turbo.StreamActions.update_input = function () {
this.targetElements.forEach((target) => {
target.value = this.templateContent.textContent
});
};
# app/views/users/_form.html.erb
<%= form_with model: @user do |f| %>
<%= f.text_field :name %>
<%= f.submit %>
<% end %>
# app/controllers/users_controller.rb
def update
helpers.fields model: @user do |f|
render turbo_stream: turbo_stream.action(
:update_input, f.field_id(:name), "new value"
)
end
end
https://translate.google.com/translate?hl=ja&sl=en&tl=ja&u=https://turbo.hotwired.dev/handbook/streams#custom-actions
別の例が必要な場合は、次のようにします。 https://translate.google.com/translate?hl=ja&sl=en&tl=ja&u=https://stackoverflow.com/a/76112894/207090