加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何为组合字段的唯一性建模此复杂验证

发布时间:2020-12-16 23:07:27 所属栏目:百科 来源:网络整理
导读:链接有两个组件:componenta_id和componentb_id.为此,在Link模型文件中我有: belongs_to :componenta,class_name: "Component"belongs_to :componentb,class_name: "Component"validates :componenta_id,presence: truevalidates :componentb_id,presence:
链接有两个组件:componenta_id和componentb_id.为此,在Link模型文件中我有:
belongs_to :componenta,class_name: "Component"
belongs_to :componentb,class_name: "Component"

validates :componenta_id,presence: true
validates :componentb_id,presence: true
validates :componenta_id,uniqueness: { scope: :componentb_id }
validates :componentb_id,uniqueness: { scope: :componenta_id }

并在迁移文件中:

create_table :links do |t|
  t.integer  :componenta_id,null: false 
  t.integer  :componentb_id,null: false
  ...
end
add_index :links,:componenta_id
add_index :links,:componentb_id
add_index :links,[:componenta_id,:componentb_id],unique: true

问题:这一切都有效.现在我希望componanta和componentb的组合是独一无二的,无论它们的顺序如何.因此,无论哪个组件是组件a,哪个组件是组件b(毕竟这是相同的链接;两个相同组件之间的链接).因此,不应允许下面的两个记录,因为它们代表相同的链接,因此不是唯一的:

> componenta_id = 1; componentb_id = 2
> componenta_id = 2; componentb_id = 1

如何创建此唯一性验证?我有模型验证工作(见下文),但想知道是否以及如何在迁移/数据库级别添加验证…?

模型验证
我使用以下代码进行模型验证:

before_save :order_links
validates :componenta_id,uniqueness: { scope: :componentb_id }

private
  def order_links
    if componenta_id > componentb_id
      compb = componentb_id
      compa = componenta_id
      self.componenta_id = compb
      self.componentb_id = compa
    end
  end

以下测试证实了上述工作:

1. test "combination of two links should be unique" do
  2.   assert @link1.valid?
  3.   assert @link2.valid?
  4.   @link1.componenta_id = 3     #@link2 already has combination 3-4
  5.   @link1.componentb_id = 4
  6.   assert_not @link1.valid?
  7.   @link1.componenta_id = 4
  8.   @link1.componentb_id = 3
  9.   assert_raises ActiveRecord::RecordNotUnique do
  10.    @link1.save
  11.  end
  12.end

迁移/数据库验证:
作为额外的安全级别,是否还有一种方法可以在db级别上对此进行验证?否则,仍然可以将以下两个记录写入数据库:componenta_id = 1; componentb_id = 2以及componenta_id = 2; componentb_id = 1.

解决方法

也许可以通过以下方式控制链接的创建:
def create_unique_link( comp_1,comp_2 )
  if comp_1.id > comp_2.id
    first_component = comp_1
    second_component = comp_2
  end
  link = Link.find_or_create_by( componenta_id: first_comp.id,componentb_id: second_comp.id )
end

如果您需要验证,那么您可以自定义验证:

def ensure_uniqueness_of_link
  if comp_1.id > comp_2.id
    first_component = comp_1
    second_component = comp_2
  end

  if Link.where( componenta_id: first_component.id,componentb_id: second_component ).first
    errors.add( :link,'Links should be unique' )
  end

end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读