通过更改其他项目的状态来保证唯一性



我有一个具有布尔属性的页面模型:is_root。如果此值设置为 true,则此值应该是唯一的,因此,通过在一个项目上将其设置为 true,其他将此设置为 true 的项目应改为设置为 false。它只是交换活动项目。

有没有优雅的"轨道"方法来做到这一点?目前我正在使用这个:

class Page < ActiveRecord::Base
  attr_accessible :is_root
  before_save :guarantee_uniqueness_of_is_root
  def guarantee_uniqueness_of_is_root
    if self.is_root?
      Page.where(:is_root => true).each do |p|
        p.update_attribute(:is_root, false) if p != self
      end
    end
  end
end

结束

但这对我来说似乎很丑陋。

感谢您的帮助:)

阿恩

我认为

,您正在寻找的不是完全:)的唯一性,而是一次只存在一个根页面,因此当页面添加为root时,重置现有根页面,确保任何时候都只有一个根页面。

否则,人们怎么能想象布尔列是唯一的:)只有两条记录:)

class Page < ActiveRecord::Base
  attr_accessible :is_root
  before_save :ensure_single_root_page
  def ensure_single_root_page
    Page.update_all(:is_root => false) if self.is_root?
  end
end

此外,我建议,如果您可以将根页面 ID 存储在其他地方,例如设置表或这些页面所属的其他表。有这样一个布尔列是不好的,你知道is_root列中的所有值都是假的,只有一个是真的。

最新更新