2015-09-05 24 views
1

我有articlecomment模型。如何显示关联模型中的错误?

我想这样写:

= form_for ([@article, @article.comments.build]) do |f| 
    - if @article.comments.errors.any? 
    %h4 Errors 
    %ul 
     - @article.comments.errors.full_message do |message| 
     %li= message 

,但我得到的错误:

undefined method `errors' for Comment::ActiveRecord_Associations_CollectionProxy:0x9a4a020

Article有许多意见和comment属于文章。

我想为我的评论显示验证错误。

编辑: 我comment型号:

class Comment < ActiveRecord::Base 
    belongs_to :article 
    validates :author, presence: true, length: { minimum: 3 } 
    validates :body, presence: true, length: { minimum: 5 } 
end 
+0

'@ article.comments.first.'? –

+0

现在没有错误。但验证错误不会显示时应该(模型中我有存在验证等)。 – Jensky

+0

显示您在模型中写入的验证 –

回答

1

不能调用错误的集合像@article.comments

在你的控制器,征求意见创建一个实例变量:

def new 
    @comment = @article.comments.build 
end 

def create 
    @comment = @article.comments.build 
    respond_to do |format| 
    if @comment.save 
    # handle save 
    else 
    format.html { render :new } 
    format.json { render json: @comment.errors, status: :unprocessable_entity } 
    end 
    end 
end 

然后更新您的形式:

= form_for ([@article, @comment]) do |f| 
    - if @comment.errors.any? 
    %h4 Errors 
    %ul 
     - @comment.errors.full_message do |message| 
     %li= message