2015-09-05 34 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