我有帖子,我允許別人評論它。問題是,如果有人試圖發佈空白評論,他們收到此錯誤信息:如何在輸入空白評論時防止此錯誤? (Ruby on Rails 3)
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
我認爲驗證:comment_content會阻止任何人從空白提交中收到任何錯誤消息,但上面的錯誤消息出現。
這是我CommentsController
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
'post'變量是如何來到這裏的'form_for([post,@comment]'?它在哪裏定義的? – HungryCoder
它的定義d在CommentsController中。我將在一秒內更新上面的內容 –
然後它將是'@ post' not'post' – HungryCoder