stimulus-rails-ujs v1.0.3
Stimulus Rails UJS
Stimulus controller to provide integration with Rails UJS
Installation
$ yarn add stimulus-rails-ujsUsage
Register the controller with Stimulus:
// application.js
import { Application } from 'stimulus';
import { RailsUJSController } from 'stimulus-rails-ujs'
const application = Application.start()
application.register('rails-ujs', RailsUJSController)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.submitIn the Rails controller, you will need to modify your response:
def create
@model = Model.new model_params
if @model.save
redirect_to models_path, notice: 'Success!'
else
render partial: 'form', status: :unprocessable_entity
end
endYou 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.submitMethods
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.submitsuccess
The success method can be used to render a response to anywhere on the page.
Params
data-response-targeta CSS selector where the response will godata-placementone ofappend|prepend|replace|replace_innerappendandprependwill append/prepend the response to thedata-response-targetreplacewill replace the entiredata-response-target(outerHTML)replace_innerwill 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.submitsubmit
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.submitContributing
Fork the project.
Install dependencies
$ yarn installStart the test watcher
$ yarn test:watchRunning one-off test runs can be done with:
$ yarn testWrite some tests, and add your feature. Send a PR.