0

我希望我的应用程序中的每个用户都可以只添加两张图片,但只有一张是可见的,所以我在图片表中添加了一个名为“可见”的列:

def change
   create_table :pictures do |t|
     t.string :picture
     t.boolean :visible, default: true
     t.timestamps
   end
end

然后我需要类似的东西:

user has_two :pictures

最后我需要如果他添加第二张图片,第一张应该设置为visibile=false,新的设置为visible=true。

当他尝试添加另一张图片(第三张)时,我应该用visibile == true新的图片替换

做这样的事情的方法是什么,以及我如何实现(has_two)关联

4

1 回答 1

0

我可以想到两种方法来处理这个

验证

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
于 2013-09-30T02:21:52.110 回答