So I'm trying to implement a chat on my website in rails 4, following this tutorial ==> http://josephndungu.com/tutorials/gmail-like-chat-application-in-ruby-on-rails
However, I'm encountering a problem when posting a new message in the chat: The form is submited normally (as html) and this results in a missing template error for messages/create, which is to be expected since I don't have a show.html.erb Since I want to submit the form though ajax, I do have a file called show.js.erb
Here's the part that generates the form:
<div class="chatboxinput">
<%= form_for([@conversation, @message], :remote => true, :authenticity_token => true, :html => {id: "conversation_form_#{@conversation.id}"}) do |f| %>
<%= f.text_area :body, class: "chatboxtextarea", "data-cid" => @conversation.id %>
<% end %>
</div>
Here is my message controller:
class MessagesController < ApplicationController
before_filter :authenticate_user!
def create
@conversation = Conversation.find(params[:conversation_id])
@message = @conversation.messages.build(message_params)
@message.user_id = current_user.id
@message.save!
@path = conversation_path(@conversation)
end
private
def message_params
params.require(:message).permit(:body)
end
end
I'm suspecting a problem with jquery_ujs, since before that I had a problem with another ajax request who wesn't sending the csrf token properly, I had to add a line of js to fix it.
So here's the application.js
//= require jquery
//= require jquery_ujs
//= require chat
//= require jquery.turbolinks
//= require private_pub
//= require bootstrap-sprockets
//= require bootstrap-datepicker
//= require_tree .
and the application head section
<meta content='<%= user_signed_in? ? current_user.id : "" %>' name='user-id'/>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= stylesheet_link_tag '//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= yield(:head ) %>
I've been scratching my head for hours... Any insight?
Thanks in advance! :)
I've finally managed to make it work. It turns out it was related to jquery_ujs in the end. The form wasn't submited through ajax properly, so rails was looking for an .html.erb template instead of the .js.erb that I had.
I solved it by including jquery_ujs as the very last line of my appalication.js manifest (even after require_tree).
//= require jquery
//= require users
//= require private_pub
//= require bootstrap-sprockets
//= require bootstrap-datepicker
//= require_tree .
//= require jquery_ujs
//= require jquery.turbolinks
Hope this helps others!