【发布时间】:2016-05-22 21:20:29
【问题描述】:
我有一个包含文章的简单博客应用。每篇文章都有cmets。我正在尝试使用 closure_tree gem 构建嵌套的 cmets。我一直在松散地关注this sitepoint tutorial。
我有以下代码:
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/cmets/new.html.erb
<%= render "form" %>
views/cmets/_form/html.erb
<%= form_for ([@comment.article_id, @article]) do |f| %>
<%= f.text_field :title %>
<%= f.text_area :body %>
<%= f.submit %>
<% end %>
controllers/cmets_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
当我点击 articles/show.html.erb 中的link_to 以回复现有评论时,我按预期点击了new 操作并传递了评论的parent_id和article_id 也符合预期的参数。
当我离开new 操作时,问题就出现了。我希望点击表单部分,然后进入create 操作以发表评论。相反,我以某种方式为Article 打了update 操作,即使我的ArticlesController 中什至没有。我是一个 Rails 菜鸟,我认为我的嵌套路线搞砸了。任何帮助将不胜感激。
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4