2010-09-14 28 views
10

Tôi có 3 kiểu: Người dùng, Swatch + Màu. Người dùng có nhiều mẫu màu và một mẫu màu tham chiếu màu.Làm cách nào để hiển thị lỗi xác thực từ mô hình được liên kết trong Rails?

Người dùng tạo các mẫu trên trang tiểu sử của họ (người dùng/hiển thị/id).

Mẫu màu xử lý xác thực thông qua mẫu swatch với accepts_nested_attributes_for :colorvalidates_associated :color.

Câu hỏi của tôi là, cách hiển thị lỗi xác thực màu cụ thể trên trang Tiểu sử người dùng?

Đây là bộ điều khiển swatches. Tôi hiện chỉ hiển thị một thông báo lỗi chung chung với đèn flash, nhưng muốn truy cập lỗi các ActiveRecord thực :: từ mô hình màu:

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 

Trả lời

24

Bạn có thể thử

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

Tôi cũng nghĩ rằng với validates_associated, các @swatch.errors cũng chứa lỗi cho màu sắc.

+1

@ swatch.errors chỉ chứa các lỗi từ mẫu swatch – meleyal

Các vấn đề liên quan