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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With