评论部分不会保存评论

时间:2019-02-23 15:01:00

标签: ruby-on-rails ruby haml

我在Rails应用程序中做了一个评论部分,但是当我发表评论并且页面被重新加载时,评论不会被保存。我没有任何错误。

在route.rb中有此文件:

resources :analyses, only: [:index, :create, :show, :destroy, :update] do
    collection do
      post :destroy_multiple
      get :start_multiple
      post :custom_create
    end

    member do
      resources :comparisons, only: :show, param: :document_id
    end

      resources :comments
  end

然后:

class Comment
  include Mongoid::Document
  field :name, type: String
  field :body, type: String
  embedded_in :analysis
  belongs_to :analysis
end

在:

class Analysis
  embeds_many :comments

然后:

class CommentsController < ApplicationController
  def create
    @analysis = Analysis.find(params[:analysis_id])
    @comment = @analysis.comments.create(params[:comment].permit(:name, :body))
    redirect_to analyses_path(@analysis)
  end

  def destroy
    @analysis = Analysis.find(params[:analysis_id])
    @comment = @analysis.comments.find(params[:id])
    @comment.destroy
    redirect_to analyses_path(@analysis)
  end
end

_comment.haml:

%p= comment.name
%p= comment.body
%p= time_ago_in_words(comments,created_at)
%p
  = link_to 'Delete',[comment.analysis, comment], method: :delete, data: { confirm: 'Are you sure you want to delete this comment?' }

和_form.haml:

= form_for([@analysis,@analysis.comments.build]) do |f|
  %p
    = f.label :name
    = f.text_field :name
  %p
    = f.label :body
    %br/
    = f.text_area :body
  %br/
  %p
    = f.submit

,然后在analyses / show.html.haml中输入:

%br/
= @analysis.comments.count
Comments
= render @analysis.comments
%h5
Add a Comment:
= render 'comments/form'

我在没有看到评论的地方犯了错误,还是必须以不同的方式来做所有事情?

编辑:

Started POST "/analyses/2d1234c6543bca03s444des7/comments" for **** at 2019-02-23 16:28:09 +0100
Processing by CommentsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"***==", "comment"=>{"name"=>"fefwefew", "body"=>"dfwedew"} "commit"=>"Create Comment", "analysis_id"=>"2d1234c6543bca03s444des7"}
MONGODB | localhost:80000 | ***.find | STARTED | {"find"=>"analyses", "filter"=>{"_id"=>BSON::ObjectId('2d1234c6543bca03s444des7')}}
MONGODB | localhost:80000 | ***.find | SUCCEEDED | 0.008967s
Redirected to http://localhost:3000/analyses.2d1234c6543bca03s444des7
Completed 302 Found in 47ms

1 个答案:

答案 0 :(得分:0)

尝试一下:

  def create
    @analysis = Analysis.find(params[:analysis_id])
    @comment = @analysis.comments.create(comment_params)
    redirect_to analyses_path(@analysis)
  end

  private 

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