Once the form is submitted, I'd like to seamlessly add the newly saved record to my existing div that holds all the records. If there's a better method for accomplishing this, please let me know.
I'm unsure of the correct approach to achieve this, so the code in my create.js.erb file is purely speculative at this point.
The Form
<%= form_for @comment, remote: "true" do |f| %>
<%= f.hidden_field :chat_id, value: @chat.id %>
<%= f.text_area :content %>
<%= f.submit "Send" %>
<% end %>
The Controller
def create
@comment = Comment.new(creation_params)
@comment.user_id = current_user.id
if @comment.save
respond_to do |format|
format.js
format.html
end
else
redirect_to root_path
end
end
The create.js.erb File
$("#comments").append("<%= @chat.comments.last %>");
$('#comment_content').val('').focus();
The Comments Section
<ul id="comments">
<% @chat.comments.each do |comment| %>
<li id="comment-<%= comment.id %>">
<%= comment.user.name %>
<%= comment.content %>
</li>
<% end %>
</ul>