【发布时间】:2012-07-01 14:02:10
【问题描述】:
我有一个具有布尔属性的页面模型:is_root。如果此值设置为 true,则该值应该是唯一的,因此通过在一个项目上将此设置为 true,其他将此设置为 true 的项目应设置为 false。它只是交换活动项目。
有没有优雅的“rails”方式来做到这一点?目前我正在使用这个:
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
结束
但这对我来说似乎很丑。
感谢您的帮助:)
阿恩
【问题讨论】:
-
我会将 self 排除在
Page.where方法中,因此:.where('is_root = true and id != ?', self.id),并且可能会建议.update_all(:is_root => false)而不是循环,但我想不出比这更好的方法笼统地说。
标签: ruby-on-rails-3 validation activerecord unique