Even if you use form_with
without local: true
, the error message part is usually not asynchronous.
I tried to display it asynchronously, so I will summarize the method.
If you do not add local: true
to form_with
, communication will occur asynchronously.
erb:app/views/tests/new.html.erb
<%= form_with model: @test do |f| %>
<%= f.text_field :name %>
<%= render 'shared/err_msg' %>
<%= f.submit %>
<% end %>
erb:app/views/shared/err_msg.html.erb
<div id='err_container' style='display: none'>
<ul id='err_ul'>
<!--I get an error message here-->
</ul>
</div>
Controller
When @ test.save
fails, normally render: new
is used to display the view file for the new action, but here it is described in ʻapp / views / shared / err_msg.js.erb`. I am trying to execute JavaScript.
app/controller/tests_controller.rb
def index
@test = Test.new
end
def create
@test = Test.new(test_params)
respond_to do |format|
if @test.save
format.js { redirect_to tests_url, notice: 'created' }
else
@object = @test
format.js { render 'shared/error', status: :unprocessable_entity } #Status in the browser_Returns code 422
end
end
end
private
def test_params
params.require(:test).permit(:name)
end
The style of the entire error message has been changed from display: none
to display: block
, and the error message is wrapped in li
and displayed.
js:app/views/shared/err_msg.js.erb
let err_container = document.getElementById('err_container');
err_container.style.display = 'block';
let err_ul = document.getElementById('err_ul');
<% @object.errors.full_messages.each do |msg| %>
err_ul.insertAdjacentHTML('afterbegin', '<li><%= msg %></li>');
<% end %>
Recommended Posts