2016-02-11 62 views
0

我有一個簡單的博客應用程序有文章。每篇文章都有評論。我正在嘗試使用closure_tree創建嵌套註釋。我一直鬆散跟隨this sitepoint tutoriallink_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_idarticle_id也符合預期的參數。

當我離開new操作時出現問題。我希望打到部分形式,然後進入create行動以發表評論。相反,我以某種方式觸及Articleupdate操作,即使我的ArticlesController中甚至沒有。我是一個Rails noob,我想我在我的嵌套路線中搞亂了。任何幫助將非常感激。

回答

0

我嘗試在控制器中創建一個動作'子註釋'或'子'。像這樣的'post article /:id/comments /:id/child'。

resources :articles do 
    resources :comments do 
    post :child 
    end 
end 

在行動孩子這樣的事情。

def child 
    @article = Article.find(params[:article_id] 
    @comment = @article.comments.find(params[:comment_id]) 
    @child_comment = @comment.children.build(comment_params) 
    redirect_to article_path(@article) 
end 

該視圖是其他問題。迭代articles.comments和comments.children,然後使用url child_article_comment_path(@article,@comment)創建一個表單。