Stimulus Rails UJS
Stimulus controller to provide integration with Rails UJS
Installation
$ yarn add stimulus-rails-ujs
Usage
Register the controller with Stimulus:
// application.js; const application = Applicationstartapplication
Initialize the controller on a container element, and an action to render form errors:
= form_with model: @model, data: { controller: 'rails-ujs', action: 'ajax:error->rails-ujs#error' } do |f| = f.text_field :field_name = f.submit
In the Rails controller, you will need to modify your response:
@model = Model.new model_params if @model.save redirect_to models_path, notice: 'Success!' else render partial: 'form', status: :unprocessable_entity endend
You can see that the form partial has been separated so it is the only thing returned in the response. The response also sets an Unprocessable Entity HTTP Status Code (422). This is important so that Rails UJS emits a 'ajax:error' event.
Options
data-rails-ujs-load-scripts
Setting this attribute on the controller element will eval() scripts in the response if set. This is intentionally off by default.
Example
= form_with model: @model, data: { controller: 'rails-ujs', action: 'ajax:error->rails-ujs#error', rails_ujs_load_scripts: true } do |f| = f.text_field :field_name = f.submit
Methods
error
The error method is used to render the form back to the page with error messages.
Example
= form_with model: @model, data: { controller: 'rails-ujs', action: 'ajax:error->rails-ujs#error' } do |f| = f.text_field :field_name = f.submit
success
The success method can be used to render a response to anywhere on the page.
Params
-
data-response-target
a CSS selector where the response will go -
data-placement
one ofappend|prepend|replace|replace_inner
append
andprepend
will append/prepend the response to thedata-response-target
replace
will replace the entiredata-response-target
(outerHTML)replace_inner
will replace the contents ofdata-response-target
(innerHTML)
Example
%ul#response %li An existing content piece = form_with model: @model, data: { controller: 'rails-ujs', action: 'ajax:success->rails-ujs#success', placement: 'append', response_target: '#response' } do |f| = f.text_field :field_name = f.submit
submit
The submit method can be called anywhere. A good example would be to submit the form on change of an element where you want the entire form submitted.
Example
= form_with model: @model, data: { controller: 'rails-ujs', action: 'ajax:error->rails-ujs#error' } do |f| = f.text_field :field_name = f.check_box :option, data: { action: 'change->rails-ujs#submit' } = f.submit
Contributing
Fork the project.
Install dependencies
$ yarn install
Start the test watcher
$ yarn test:watch
Running one-off test runs can be done with:
$ yarn test
Write some tests, and add your feature. Send a PR.