嵌套资源的link_to重定向错误

时间:2016-02-11 21:35:05

标签: ruby-on-rails ruby ruby-on-rails-4

我有一个简单的博客应用程序,有文章。每篇文章都有评论。我正在尝试使用closure_tree gem构建嵌套注释。我一直在松散地关注this sitepoint tutorial

我有以下代码:

模型/ 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

当我点击文章/ show.html.erb 中的link_to以回复现有评论时,我按预期点击new操作并通过了评论的parent_idarticle_id也符合预期的参数。

当我离开new动作时出现问题。我希望点击表格,然后进入create行动进行评论。相反,即使我update中没有Article,我也会以某种方式点击ArticlesController的{​​{1}}动作。我是一个很好的Rails菜鸟,我想我在嵌套路线上搞乱了。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我尝试在控制器中创建一个动作'子注释'或'子'。像这样的帖子文章/: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.com和comments.children并使用url child_article_comment_path(@ article,@ comment)创建一个表单。

相关问题