I'm following the DevWalks tutorial Let's Build Instagram part 2, only I'm using rails 3 for some reason. He uses 4.
Anyway, I'm trying to get comments to ajax/jquery in there instead of refreshing the page. Here is my form:
<div class="comment-form col-sm-11">
<%= form_for([post, post.comments.build], remote: true) do |f| %>
<%= f.text_field :content, placeholder: 'Add a comment...' %>
<% end %>
</div>
Here is my comment_controller.rb:
class CommentsController < ApplicationController
before_filter :set_post
def create
@comment = @post.comments.build(comment_params)
@comment.user_id = current_user.id
if @comment.save
respond_to do |format|
format.html { redirect_to root_path }
format.js { render :layout => false }
end
else
flash[:alert] = "Check the comment form, something went wrong."
render root_path
end
end
private
def comment_params
params[:comment]
end
end
Here's the comments/create.js.erb
console.log('getting to create.js') // this never runs
$('#comments_<%= @post.id %>').append("<%=j render 'comments/comment', post: @post, comment: @comment %>");
$('#comment_content_<%= @post.id %>').val('')
And here is the feedback from the console:
Started POST "/posts/13/comments" for 127.0.0.1 at 2015-07-21 15:14:18 -0700
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"11/Ys+Xu1XhcJdGIz+I+wodYKn2xcYRTb6CEcH1PPUo=", "comment"=>{"content"=>"fewfewfew"}, "post_id"=>"13"}
Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1 [["id", "13"]] User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1 (0.1ms) begin transaction SQL (0.9ms) INSERT INTO "comments" ("content", "created_at", "post_id", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?) [["content", "fewfewfew"], ["created_at", Tue, 21 Jul 2015 22:14:18 UTC +00:00], ["post_id", 13], ["updated_at", Tue, 21 Jul 2015 22:14:18 UTC +00:00], ["user_id", 1]] (1.1ms) commit transaction
Redirected to http://localhost:3000/ Completed 302 Found in 8ms (ActiveRecord: 2.6ms)
As you can see, it is processing as HTML, so it follows that it would refresh, but given that I have 'remote: true' in my form, shouldn't that not be happening?
Any help would be much appreciated.
Aucun commentaire:
Enregistrer un commentaire