首页 > 解决方案 > Rails 5.1 中的评论路线

问题描述

我正在尝试在 Rails 5.1 中创建用户创建文章的评论。提交评论后,重定向应该是到“/articles/:id”,而是重定向到“/articles/:id/comments”。

我在 routes.rb 中使用嵌套路由:

  devise_for :users
  root to: "articles#index"

  resources :articles do
    resources :comments
  end

我的评论控制器.rb:

class CommentsController < ApplicationController
  before_action :set_article

  def create
    unless current_user
      flash[:alert] = "Please sign in or sign up first"
      redirect_to new_user_session_path
    else
      @comment = @article.comments.build(comment_params)
      @comment.user = current_user

      if @comment.save
        flash[:notice] = "Comment has been created"
      else
        flash.now[:alert] = "Comment not created correctly"
      end
      redirect_to article_path(@article)
    end
  end

  private
    def comment_params
      params.require(:comment).permit(:body)
    end

    def set_article
      @article = Article.find(params[:id])
    end
end

article/show.html.erb 中的评论表单:

<!--Start of comments-->
<div class="col-md-12">
  <%= form_for [@article, @comment],
               :html => {class: "form-horizontal", role: "form"} do 
                  |f| %>
    <% if @comment.errors.any? %>
     <div class="panel panel-danger col-md-offset-1">
       <div class="panel-heading">
         <h2 class="panel-title">
           <%= pluralize(@comment.error.count, "error") %>
           prohibited this comment from being saved:
         </h2>
         <div class="panel-body">
          <ul>
            <% @comment.errors.full_messages.each do |msg| %>
              <li><%= msg %></li>
            <% end %>
          </ul>
         </div>
       </div>
     </div>
    <% end %>

    <div class="form-group">
      <div class="control-label col-md-2">
        <%= f.label :body, 'New Comment' %>
      </div>
      <div class="col-md-10">
       <%= f.text_area :body, rows: 10, class: "form-control", placeholder: "New Comment" %>
      </div>
    </div>

    <div class="form-group">
      <div class="col-md-offset-2 col-md-10">
        <%= f.submit "Add Comment", class: "btn btn-primary btn-lg pull-right" %>
      </div>
    </div>

  <% end %>
</div>

如何使此提交按钮保存并重定向回“文章/:id”?提前致谢。

标签: ruby-on-rails-5

解决方案


路由器中生成的路由将如下所示:

/articles/:article_id/comments/:id

这意味着,当您需要在 CommentsController 中加载文章时,您应该执行以下操作(如 @Marlin 建议的那样):

def set_article
  @article = Article.find(params[:article_id])
end

否则,如果评论和文章表中的 ID 之间发生 ID 冲突,您将面临将评论附加到不正确文章的风险。或者你只是得到一个ActiveRecord::RecordNotFound错误。

但是我知道,这并不能直接回答您的问题,但我怀疑问题是由于上述原因,您从某处的数据库中加载了错误的记录。

尝试更新您的代码并编写测试,以确保您可以以编程方式重现错误:)


推荐阅读