おそらくjquery-ujs
(Rails 5.0 のデフォルト以下) を使用している場合、Mikhail が既に回答したように、カスタム jquery イベントのトリガーが機能します。
$("#new_subscription").trigger("submit.rails");
2017 年にこの質問に出くわし、Rails 5.1 を使用している人にとっては、答えは異なるでしょう。Rails 5.1 はjquery
依存関係がなくなったためjquery-ujs
、完全に書き直されrails-ujs
た . 参照: http://weblog.rubyonrails.org/2017/4/27/Rails-5-1-final/
そのため、rails-ujs で適切なCustomEvent オブジェクトをトリガーする必要があります。
現時点では、ドキュメンテーション (RailsGuides とも呼ばれます) でそれを行うための公開された方法や推奨される方法はありませんが、Rails のソース コードを見るだけで使用できるいくつかのオプションがあります。
使用Rails.fire
機能:
nativeFormEl = $("#new_subscription")[0] // you need the native DOM element
Rails.fire(nativeFormEl, 'submit')
プログラムでRails.handleRemote
ハンドラーを呼び出すこともできます (実際にdata-remote=true
XHR 経由でフォームを送信するハンドラー:
nativeFormEl = $("#new_subscription")[0] // you need the native DOM element
Rails.handleRemote.call(nativeFormEl, event); // unfortunately, you cannot reference the previously created submit CustomEvent object by rails-ujs.js
// ... or ...
Rails.handleRemote.call(nativeFormEl) // submits via XHR successfully, but throws an error after success callback at Rails.stopPropagation
私はオプション 1 を好みます。それは、最近の Web API メソッドを使用する単なるラッパーであるためです。つまり、 を作成してviaCustomEvent
にディスパッチします。EventTarget
dispatchEvent