Ruby on rails 3 通过更改其他项目来保证唯一性';s州
我有一个具有布尔属性的页面模型:is_root。如果该值设置为true,则该值应该是唯一的,因此通过在一个项目上将其设置为true,其他将此设置为true的项目应改为false。它只是交换活动项 有什么优雅的“rails”方法可以做到这一点吗?目前我正在使用这个:Ruby on rails 3 通过更改其他项目来保证唯一性';s州,ruby-on-rails-3,validation,activerecord,unique,Ruby On Rails 3,Validation,Activerecord,Unique,我有一个具有布尔属性的页面模型:is_root。如果该值设置为true,则该值应该是唯一的,因此通过在一个项目上将其设置为true,其他将此设置为true的项目应改为false。它只是交换活动项 有什么优雅的“rails”方法可以做到这一点吗?目前我正在使用这个: class Page < ActiveRecord::Base attr_accessible :is_root before_save :guarantee_uniqueness_of_is_root def g
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
class页面true)。每个do | p|
p、 如果p!=自己
结束
结束
结束
结束
结束
但我觉得这很难看
谢谢你的帮助:)
Arne我认为,您要寻找的不是唯一性:),而是一次只存在一个根页面,因此当一个页面被添加为根页面时,请重置现有根页面,确保在任何时候都只存在一个根页面 否则,我们怎么能想象一个布尔列是唯一的:)只有两条记录:)
class页面false)?
结束
结束
此外,我建议,如果您可以将根页面id存储在其他地方,比如设置表,或者这些页面所属的其他表。有这样一个布尔列是不好的,您知道is_root列中的所有值都是false,只有一个值是true。我会将self的排除移到
页面。where
方法,因此:。where('is_root=true and id!=?',self.id)
,并可能建议。update_all(:is_root=>false)
而不是循环,但我想不出比这更好的方法。
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