I'm working on a Rails application similar to a comments board and I want to incorporate ajax functionality. However, my code is not functioning as expected and I can't seem to pinpoint the issue...
Here is the code from my controller:
# controller/article_controller.rb
def show
@comments = Comment.where(article_id:params[:id])
end
def comment
@comment = Comment.new(comment_params)
respond_to do |format|
if @comment.save
@comments = Comment.where(article_id:params[:id])
format.js
else
render 'show'
end
end
end
private
def comment_params
params.require(:comment).permit(:comment)
end
The corresponding view looks like this:
views/article/show.slim
= form_for(@comment, url: comment_path, data: { remote: true }) do |f|
= f.text_area :comment
= f.submit 'create'
#board_comments
= render partial: 'comment', locals: { comments: @comments }
For the partial template in views/article/_comment.slim:
- comments.try(:each) do |comment|
p = comment[:comment]
The JavaScript file views/article/comment.js.slim contains:
| $('#board_comments').html("#{j render(partial: 'article/comment', locals: { comments: @comment }) }");
| $('#comment_comment').val('');
Can anyone help identify what may be causing the issue in my code?
Some relevant logs:
Started POST "/article/9/comment" for 127.0.0.1 at 2014-08-04 00:31:05 +0900
Processing by ArticleController#comment as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"FJYVadfpYoZc7OPdk68guKxiPLKdYb2LkQJfKVKRZw=", "comment"=>{"comment"=>"1234"}, "commit"=>"create", "id"=>"9"}
(0.5ms) BEGIN
SQL (6.3ms) INSERT INTO `comments` (`comment`, `created_at`, `updated_at`, `user_id`, `article_id`) VALUES ('1234', '2014-08-03 15:31:05', '2014-08-03 15:31:05', 1, 9)
(2.2ms) COMMIT
Comment Load (0.5ms) SELECT `comments`.* FROM `comments` WHERE `comments`.`article_id` = 9
Rendered article/_comment.slim (1.0ms)
Rendered article/comment.js.slim within layouts/application (38.0ms)
Rendered shared/_menu.html.slim (1.9ms)
Rendered layouts/_ga.slim (0.3ms)
Completed 200 OK in 213ms (Views: 159.1ms | ActiveRecord: 9.5ms)
The layout file views/layouts/application.slim includes:
doctype html
html
head
= stylesheet_link_tag 'application', media: 'all'
= javascript_include_tag 'application'
= favicon_link_tag('favicon.ico')
= csrf_meta_tags
body
= render 'shared/menu'
= yield
= render 'layouts/ga'