Currently, I have a 'projects/show.html.erb' page where a project has many 'project_messages'. Users can successfully create new project messages on this page. However, there is an issue where the page refreshes when creating a new project message using a '_form' partial.
To address this, I attempted to use ':remote => true' in order to add project messages without refreshing the page. Unfortunately, the code I used did not work as expected and the page still refreshed. As I am relatively new to rails, any assistance or guidance would be highly appreciated.
Below are the codes for each respective file:
In 'projects/show.html.erb', the following code is used to display and create project messages:
<div class="au-chat au-chat--border">
<div class="au-message-list">
<% @project.project_messages.each do |project_message| %>
<%= render partial: 'project_messages/project_message', locals: { project_message: project_message } %>
<% end %><br>
</div>
<div class="au-chat-textfield">,
<%= render partial: 'project_messages/form', locals: { project_message: @project_message } %>
</div>
</div>
In the 'project_messages_controller.rb' file, the create method includes 'format.js { }
' like so:
def create
@project_message = ProjectMessage.new(project_message_params)
@project_message.user_id = current_user.id if current_user
@project_message.project_id = current_user.team.project_id if current_user
respond_to do |format|
if @project_message.save
format.html { redirect_to @project_message.project }
format.json { render :show, status: :created, location: @project_message }
format.js { }
else
format.html { render :new }
format.json { render json: @project_message.errors, status: :unprocessable_entity }
end
end
end
The 'project_message' '_form' partial includes ':remote => true' as shown below:
<%= form_with(model: project_message, local: true, :remote => true) do |form| %>
<% if project_message.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(project_message.errors.count, "error") %> prohibited this project_message from being saved:</h2>
<ul>
<% project_message.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form.text_field :pMessage, id: :project_message_pMessage, :class => 'au-input au-input--full au-input--h65', placeholder: 'Type a message' %>
<div class="actions" >
<%= form.submit "Send" %>
</div>
<% end %>
A 'create.js.erb' file was created in views/project_messages/create.js.erb with the following content:
# confirm file called
console.log('create.js.erb file');
# add new comment to end of comments section
$("#project_message").append("<%= j render(@project_message) %>");
Despite these efforts, the page continues to refresh. Removing 'local: true' from the 'project_message' '_form' partial prevents the page from refreshing, but it also fails to update the 'projects/show.html.erb' view.
I referenced this link as well as other resources on stackoverflow during my troubleshooting process.