I have a simple blog app that has articles. Each article has comments. I'm trying to build nested comments using the closure_tree
gem. I've been loosely following this sitepoint tutorial.
I have the following code:
models/article.rb
class Article < ActiveRecord::Base
has_many :comments
end
models/comment.rb
class Comment < ActiveRecord::Base
acts_as_tree order: 'created_at DESC'
end
routes.rb
resources :articles do
resources :comments
get 'comments/new/(:parent_id)', to: 'comments#new', as: :new_comment
end
views/articles/show.html.erb
<h1><%= @article.title %></h1><br>
<h3><%= @article.body %></h3>
Comments:
<% @article.comments.each do |comment| %>
Title: <%= comment.title %>, Body: <%= comment.body %>, User: <%= comment.user_id %>
<%= link_to 'reply', article_new_comment_path(parent_id: comment.id, article_id: @article.id) %>
<% end %>
</ul>
<!-- FORM FOR NEW COMMENT -->
<%= form_for ([@article, @article.comments.build]) do |f| %>
<%= f.hidden_field :parent_id %>
<%= f.text_field :title %>
<%= f.text_area :body %>
<%= f.submit %>
<% end %>
views/comments/new.html.erb
<%= render "form" %>
views/comments/_form/html.erb
<%= form_for ([@comment.article_id, @article]) do |f| %>
<%= f.text_field :title %>
<%= f.text_area :body %>
<%= f.submit %>
<% end %>
controllers/comments_controller.rb
[...]
def new
@article = Article.find(params[:article_id])
@comment = Comment.new(parent_id: params[:parent_id])
end
def create
# binding.pry
if params[:comment][:parent_id].to_i > 0
parent = Comment.find_by_id(params[:comment].delete(:parent_id))
@comment = parent.children.build(comment_params)
else
@article = Article.find(params[:article_id])
@comment = @article.comments.create(comment_params)
[...]
end
When I click the link_to
in articles/show.html.erb in order to reply to an existing comment, I hit the new
action as expected and pass the comment's parent_id
and article_id
also as expected into params.
The problem arises when I leave the new
action. I expect to hit the form partial and then go into the create
action for a comment. Instead I'm somehow hitting the update
action for an Article
, even though I don't even have one in my ArticlesController
. I'm quite a Rails noob and I think I'm messing up in my nested routes. Any help would be much appreciated.