我有帖子,我允许人们对此发表评论。问题是,如果有人尝试发表空白评论,他们会收到以下错误消息:
NameError in Comments#create
Showing app/views/shared/_comment_form.html.erb where line #1 raised:
undefined local variable or method `post' for #<#<Class:0x6344a18>:0x635ad20>
提取的源代码(在第 1 行附近):
1: <%= form_for([post, @comment]) do |f| %>
2: <%= render 'shared/error_messages', object: f.object %>
3: <div class="field">
4: <%= f.text_field :comment_content %>
这是我在评论模型中的内容
class Comment < ActiveRecord::Base
attr_accessible :comment_content
belongs_to :user
belongs_to :post
validates :comment_content, presence: true
validates :user_id, presence: true
validates :post_id, presence: true
我认为 validates :comment_content 会阻止任何人从空白提交中收到任何错误消息,但出现了上述错误消息。
这是我的评论控制器
class CommentsController < ApplicationController
def new
@post = Post.new(params[:post])
end
def show
@comment = Comment.find(params[:id])
respond_to do |format|
format.js
end
end
def create
@post = Post.find(params[:post_id])
@comment = Comment.new(params[:comment])
@comment.post = @post
@comment.user = current_user
if @comment.save
redirect_to(:back)
else
render 'shared/_comment_form'
end
end
end