This time, we will implement the posting function by asynchronous communication. This time, we will start from the state where the posting function with screen transition is already implemented in order to focus on performing asynchronous processing. In order to understand js, it will be described in plain js. Also, since I am a beginner, I would appreciate it if you could point out any mistakes.
Let's add remote: ture to the input form!
<%#Task input form%>
<div class="task-contents">
<%= form_with model: @category, id: 'new_tasks', class: 'new_tasks' do |f| %>
<div class="task-field">
<%= f.text_field :task %>
</div>
<div class="task-actions">
<%= f.submit "+" %>
</div>
<% end %>
</div>
Where is remote: ture here? I think some people think that if you use form_with, it is specified to perform ajax communication by default, so you do not need to write anything when using form_with. On the contrary, if you do not use ajax communication, set local: true to make a normal request. If you use form_for, don't forget to add the remote: true option. If you are worried, you should check it with a development tool etc. and it should be data-remote = "true".
def create
@category = Category.new(category_params)
@category.save
@categories = current_user.categories.all
end
Although it is a description that performs a general save function, the description of @categories = current_user.categories.all is described because it is necessary as information to be passed to js after this.
Create the create.js.erb file because the content returned by remote: true is not HTML but the action name.js.erb file is read
(function(){
document.querySelector(".task-lists").innerHTML = '<%= j(render 'categories/index', categories: @categories) %>'
document.querySelector("#category_task").value = ''
})();
I am rewriting the contents of HTML with .innerHTML.
'<%= j(render 'categories/index', categories: @categories) %>' Here we have defined it in step 2 to pass @categories. document.querySelector("#category_task").value = '' This description leaves the input form empty.
This completes the asynchronous posting function! The important thing is that if you can understand the data flow of ajax communication, each process is simple and easy to understand. Since it is a beginner, I would appreciate it if you could teach me if there is a better description.
If you like articles such as asynchronous deletion, please ~ https://qiita.com/shantianchengyilang316/items/10ab2d84f6cfcfd29def
Recommended Posts