Jensky
Jensky

Reputation: 917

How to display errors from associated model?

I have article and comment model.

I want to write this:

= 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

But I get error:

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

Article has many comments and comment belongs to article.

I want to display validation error for my comment.

EDIT: My comment model:

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

Upvotes: 2

Views: 573

Answers (1)

JeffD23
JeffD23

Reputation: 9298

You can't call errors on a collection like @article.comments.

In your controller, create an instance variable for comment:

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

Then update your form:

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

Upvotes: 1

Related Questions