简体   繁体   English

如何在Rails中显示关联模型的验证错误?

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

I have 3 models: User, Swatch + Color. 我有3个型号:用户,Swatch + Color。 A user has many swatches, and a swatch references a color. 用户具有许多样本,并且样本引用颜色。

Users create swatches on their profile page (users/show/id). 用户在其个人资料页面(users / show / id)上创建样本。

The color model handles validation through the swatch model with accepts_nested_attributes_for :color and validates_associated :color . 颜色模型通过样本模型处理验证,其中包含accepts_nested_attributes_for :colorvalidates_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: 我目前只是用flash显示一个通用错误消息,但是想从颜色模型访问真正的ActiveRecord :: Errors:

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. 我还认为,使用validates_associated@swatch.errors也包含颜色错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM