EDIT - Troubleshoot first
I was thinking that your code looks fine and should work, unless you are missing some from below. So just troubleshoot two things to make sure the issue isn't something trivial.
If your JavaScript code that updates the view is inside of a function, make sure that format.js
calls that function not just the JavaScript file.
Like this:
respond_to do |format|
format.js { render :js => "my_function();" }
end
Check out this post for a more detailed example.
You also might want to have a look at these posts from people who had the same problem as you, since it should be very simple to see if you had the same issue as them:
Post 1
Post 2
Post 3
If the above troubleshooting didn't work, then have a look below.
You probably want to use AJAX if you want to actually have things happen on the back end (store a comment in the DB), and show those changes on the front end (show new comments), without a page refresh.
With Rails, AJAX is dead simple. The process of using AJAX with your Rails app so that the page doesn't have to be reloaded/refreshed has been explained and outlined in many resources. The best resource I've found, is this guide.
Since there are dead simple guides that are really good at explaining the process, I won't go into too much detail here.
It looks like you're pretty much setup for AJAX, just make sure you have everything included that I list below.
You must add remote: true
(or for earlier versions :remote => true
), to your links/buttons. This will allow the AJAX call to take place. Like this example:
<%= link_to 'Post Comment!', create_comments_path('params in here'), :remote => true %>
Or maybe if you're using a form, you can simply add the remote part to the submit tag:
<%= form_for [@post, Comment.new], remote: true do |f| %>
Of course your exact line might differ some, based on your controllers and views.
The next step is to add a respond_to..format.js..
block to your method which handles creating the comment in the DB, or whatever else you may be doing. I didn't list out the entire block since you've already got that in your code :)
Do be sure that no controller methods that get called have a format.html
line that has a body in the respond_to..
block. format.html
is fine, but format.html { #anything in here }
is not fine.
Next, we need to use make the .js file which will repopulate the view with the newly created comments (or whatever else). It looks like you've already got this file already made, so I won't talk about how to make it.
If you have any trouble, you will get the most help from these guides: