Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show validation errors from an associated model in Rails?

I have 3 models: User, Swatch + Color. A user has many swatches, and a swatch references a color.

Users create swatches on their profile page (users/show/id).

The color model handles validation through the swatch model with accepts_nested_attributes_for :color and validates_associated :color.

My question is, how to show the color-specific validation errors on the User profile page?

This is the swatches controller. I currently just show a generic error message with the flash, but would like to access the real ActiveRecord::Errors from the color model:

class SwatchesController < ApplicationController

  before_filter :authenticate

  def create 
    color = Color.find_or_create_by_value(params[:swatch][:colors][:value])    
    @swatch = current_user.swatches.build(:color_id => color.id)

    if @swatch.save
      flash[:success] = "Swatch created"
      redirect_to user_path(current_user)
    else
      flash[:error] = "Error"
      redirect_to user_path(current_user)              
    end
  end

end
like image 329
meleyal Avatar asked Sep 14 '10 21:09

meleyal


1 Answers

You may try

flash[:error] = color.errors.empty? ? "Error" : color.errors.full_messages.to_sentence

I also think that with validates_associated, the @swatch.errors also contains errors for color.

like image 76
Yannis Avatar answered Nov 16 '22 06:11

Yannis