我可以想到两种方法来处理这个
验证
class User
MAX_PHOTOS_PER_PERSON = 2
has_many :photos
validate_on_create :photos_count_within_bounds
def visible_photo
photos.find(&:visible)
end
private
def photos_count_within_bounds
return if photos.blank?
errors.add("Only #{MAX_PHOTOS_PER_PERSON} photos allowed per person") if photos.length > MAX_PHOTOS_PER_PERSON
end
end
class Photo
belongs_to :album
validates_associated :album
end
两个协会
如果您确定每人只需要两张照片,则可以使用两个 has_one 关联的更简单的解决方案
class User
has_one :visible_photo, class_name: 'Photo', -> { where visible: true }
has_one :spare_photo, class_name: 'Photo', -> { where visible: false }
def add_photo(details)
self.create_spare_photo(...details...)
end
def activate_spare_photo
visible_photo.deactivate if visible_photo
spare_photo.activate if spare_photo
# At this point, visible_photo will contain the earlier spare_photo
end
end
class Photo
def activate
self.visible = true
self.save!
end
def deactivate
self.visible = false
self.save!
end
end