如何克服这个错误 ActiveModel::ForbiddenAttributesError,我需要能够发表评论

How to get past this error ActiveModel::ForbiddenAttributesError, I need comments able to be posted

这是我的路线,

Rails.application.routes.draw do
 get 'comments/create'

 get 'comments/destroy'

 resources :posts do 
   resources :comments
 end

这是我的评论控制器,

class CommentsController < ApplicationController 
  def create 
    @post = Post.find(params[:post_id])
    @comment = @post.comments.build(params[:comment])
    @comment.save
    redirect_to @posts
  end

  def destroy 

  end
end

这是我的 Posts.rb,

class Post < ActiveRecord::Base

  has_many :comments
end

和我的 html、

<h1><%= @post.title %></h1>

<%= @post.text %>
  <h2>Comments</h2>

  <% @post.comments.each do |comment| %>
    <p><%= comment.text %></p>
    <p><%= time_ago_in_words comment.created_at %> ago </p>
  <% end %>

  <%= form_for [@post, @post.comments.build] do |f| %>
    <p><%= f.text_area :text, :size => "40x10" %></p>
    <p><%= f.submit "Post Comment" %></p>
  <% end %>

  <p>
    <%= link_to "Back", posts_path %>
    |
    <%= link_to "Edit", edit_post_path(@post) %> 
    |
    <%= link_to "Delete", @post, method: :delete, data: { confirm: 'Are you sure?' } %>
  </p>

你应该使用 strong parameters,像这样:

def create
  # ...
  @comment = @post.comments.build(comment_params)
  # ...
end
# ...
private

def comment_params
  params.require(:comment).permit(:text)
end