2013-03-30 63 views
0

我有帖子,我允許別人評論它。問題是,如果有人試圖發佈空白評論,他們收到此錯誤信息:如何在輸入空白評論時防止此錯誤? (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 
+1

'post'變量是如何來到這裏的'form_for([post,@comment]'?它在哪裏定義的? – HungryCoder

+0

它的定義d在CommentsController中。我將在一秒內更新上面的內容 –

+3

然後它將是'@ post' not'post' – HungryCoder

回答

0

因爲comment_form是一個部分,你需要通過所謂post當你渲染它,否則它不會有任何的知識在哪裏得到它的局部變量。

在你的控制器動作,改變

render 'shared/_comment_form' 

render partial: 'shared/_comment_form', locals: { post: @post } 

我不知道,如果渲染諧音的快捷方式將控制器內工作,但它是值得一試

render 'shared/_comment_form', post: @post 
+0

這會有所幫助,但我現在得到這個錯誤'Template is missing 缺少部分共享/ _comment_form {:locale => [:en],:formats => [:html],:handlers => [:erb,:builder,: arb,:coffee]}'。有沒有辦法阻止人們試圖完全發佈空白的通訊? –