views:

44

answers:

1

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
+1  A: 

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.

Yannis
@swatch.errors only contains the errors from the swatch model
meleyal