如何为组合字段的唯一性建模此复杂验证

时间:2015-12-29 12:15:06

标签: ruby-on-rails ruby validation model migration

link有两个componentscomponenta_idcomponentb_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

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

  • 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

2 个答案:

答案 0 :(得分:4)

也许可以通过以下方式控制链接的创建:

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

答案 1 :(得分:2)

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