我有一個簡單的博客應用程序有文章。每篇文章都有評論。我正在嘗試使用closure_tree
創建嵌套註釋。我一直鬆散跟隨this sitepoint tutorial。link_to爲嵌套的資源重定向不正確
我有以下代碼:
型號/ article.rb
class Article < ActiveRecord::Base
has_many :comments
end
型號/ 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
的意見/用品/ 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 %>
的意見/評論/ new.html.erb
<%= render "form" %>
的意見/評論/ _form/HTML。 erb
<%= form_for ([@comment.article_id, @article]) do |f| %>
<%= f.text_field :title %>
<%= f.text_area :body %>
<%= f.submit %>
<% end %>
個
控制器/ 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
當我點擊link_to
在文章/ show.html.erb爲了回覆現有評論,我打的是new
行動預期,並傳遞評論的parent_id
和article_id
也符合預期的參數。
當我離開new
操作時出現問題。我希望打到部分形式,然後進入create
行動以發表評論。相反,我以某種方式觸及Article
的update
操作,即使我的ArticlesController
中甚至沒有。我是一個Rails noob,我想我在我的嵌套路線中搞亂了。任何幫助將非常感激。