2015-12-30 32 views
1

我有一个Board模式,可能属于Artist,AlbumBoardCategory。我基本上想验证,如果三个父ID中的一个存在,剩下的两个不能添加到板上。因为我正在验证多个属性,所以我想知道如何设置error.add消息。更重要的是,如何在不创建如此长的基于条件的语句||的情况下实现这一目标?独家验证是否存在一个父母身份证

class Board << ActiveRecord::Base 
    belongs_to :artist 
    belongs_to :album 
    belongs_to :board_category 

    validate :board_parent 

    private 
    def board_parent 
     if artist_id.present? || album_id.present? || board_category_id.present? 
     errors.add(..., "already belongs to an artist or album" 
     end 
    end 

回答

0

试试这个:

if [artist_id, album_id, board_category_id].reduce.length > 1 
    errors.add(:board, "Cant belong to both #{[! artist_id ||'Artist', !album_id||'Album', !board_category_id ||'Board Category'].select {|x| x != true}.join(' and ')}") 
end 
0

根据您的描述,我建议您修改模型结构。 polymorphic association是你真正需要的。这里是教程:

polymorphic association