确保集合中一个对象的属性为true,并将其他对象的属性设置为false

问题描述 投票:-1回答:2

我有一个带有布尔属性的类,称为primary。我有一个唯一性验证设置,以确保仅将属于特定餐厅的集合中的一个设置为true:

validates_uniqueness_of :primary, if: :primary, scope: [:restaurant_id]

最近,我想以一种方式来自定义writer方法,即它会在分配当前实例的新值的同时,如果实例为true,则将集合中的同级设置为false。尽管如此,我的测试仍然失败:

 MenuGroup did not properly validate that :primary is case-sensitively
       unique within the scope of :restaurant_id.
         After taking the given MenuGroup, setting its :primary to ‹"an
         arbitrary value"› (read back as ‹true›), and saving it as the existing
         record, then making a new MenuGroup and setting its :primary to a
         different value, ‹true› and its :restaurant_id to a different value,
         ‹nil›, the matcher expected the new MenuGroup to be invalid, but it
         was valid instead.

这里是测试:

it { should validate_uniqueness_of(:primary).scoped_to([:restaurant_id]) }

我在这里做错了什么?

class MenuGroup < ApplicationRecord
  belongs_to :restaurant

  validates_uniqueness_of :primary, if: :primary, scope: [:restaurant_id]

  def primary=(primary)
    if primary?
      MenuGroup
       .where.not(id: self.id)
       .where(restaurant_id: self.restaurant_id).update_all(primary: false)
    end

    write_attribute :primary, primary
  end
end
ruby-on-rails activerecord
2个回答
0
投票

[if primary?检查记录的self.primary?是否为真。

?使它调用由ActiveRecord自动生成的本地primary?方法。 not检查作为函数参数传递的变量primary

也就是说,您的验证无法测试,实际上不做任何事情。

primary=设置程序的全部目的是自动取消设置先前的primary记录。您的验证无法取消,因为您的设置者阻止您的模型进入无效状态。

您的测试尝试将第二个MenuGroup设置为primary = true,但是此操作将所有现有primary = false上的设置为MenuGroup,因此验证运行并顺利进行。


-2
投票

请参阅节制理论以获取关于节制理念的信息。

[Aaron Hall♦美国纽约市222k6161金徽章330330银徽章285285青铜徽章当选2016年

[安迪♦36.7k2222金徽章1231​​23银徽章186186青铜徽章当选2017年

Baum mit Augen♦44.1k1212金徽章125125银徽章162162青铜徽章当选2019年

[Bhargav Rao♦印度卡纳塔克邦班加罗尔34.4k2222金徽章101101银徽章118118青铜徽章当选2016年

[Bohemian♦澳大利亚墨尔本326k7272金徽章463463银徽章601601青铜徽章当选2014年

[BoltClock♦新加坡568k134134金徽章12301230银徽章12481248青铜徽章当选2011年

[布拉德·拉尔森♦威斯康星州麦迪逊166k4545金徽章378378银徽章556556青铜徽章当选2012年

ChrisF♦英国120k2525金徽章230230银徽章304304青铜徽章当选2013年

Cody Gray♦美国加利福尼亚州桑尼维尔206k3838金牌418418银牌495495青铜牌当选2017年

[cece德国432k6969金徽章601601银徽章745745青铜徽章当选2016年

[Flexo♦76.5k2222金徽章163163银徽章241241青铜徽章当选2013年

[Jean-FrançoisFabre♦法国图卢兹116k1010金徽章7777银徽章133133青铜徽章当选2019年

josliber♦密歇根州39.5k1111金徽章7373银徽章109109青铜徽章当选2015年

[Madara Uchiha♦以色列146k4949金徽章229229银徽章280280青铜徽章当选2015年

[Martijn Pieters♦英国剑桥784k180180金徽章28812881银徽章25712571青铜徽章当选2015年

meagar♦192k3434金徽章290290银徽章304304青铜徽章当选2015年

[Michael Myers♦美国166k4040金徽章268268银徽章284284青铜徽章指定于2010年7月11日] >>

Rob♦澳大利亚23.8k1313金徽章6565银徽章8080青铜徽章当选2018年

[Ry-♦加拿大不列颠哥伦比亚省维多利亚市183k4343金徽章371371银徽章387387青铜徽章当选2013年

[Samuel Liew♦澳大利亚新南威尔士州59.6k3939金牌124124银牌191191青铜牌当选2019年

撤消♦24.6k2121金徽章9696银徽章

Ralph TorelloGoogle云端伺服器请参阅:Torello.Directory请参阅:Twitter.com/RalphCNB

© www.soinside.com 2019 - 2024. All rights reserved.