Ruby on rails rails中的交叉唯一性模型验证

Ruby on rails rails中的交叉唯一性模型验证,ruby-on-rails,ruby,validation,activerecord,models,Ruby On Rails,Ruby,Validation,Activerecord,Models,我有一个模型,希望列包含不同的ID。因此,一个用户可以跟随另一个用户,但不能跟随自己 迁移 class CreateFollows < ActiveRecord::Migration def change create_table :follows do |t| t.integer :follower_id t.integer :followee_id t.timestamps end end end 输出 Failures:

我有一个模型,希望列包含不同的ID。因此,一个用户可以跟随另一个用户,但不能跟随自己

迁移

class CreateFollows < ActiveRecord::Migration
  def change
    create_table :follows do |t|
      t.integer :follower_id
      t.integer :followee_id

      t.timestamps
    end
  end
end
输出

Failures:

1) Follow cannot follow itself
 Failure/Error: expect(follow).to be_invalid
   expected `#<Follow id: 27, follower_id: 78, followee_id: 78, created_at: "2014-07-04 02:20:59", updated_at: "2014-07-04 02:20:59">.invalid?` to return true, got false
 # ./spec/models/follow_spec.rb:23:in `block (2 levels) in <top (required)>'
故障:
1) 跟随不能跟随自己
失败/错误:预期(跟随)。无效
应为“#.invalid?”若返回true,则为false
#./规格/型号/遵循规格rb:23:in‘分块(2层)in’
从我所读到的一切来看,这看起来像是在写东西。有人有什么建议吗

感谢此验证:

validates :follower_id, uniqueness: { scope: :followee_id }
简单地说,每个
followee\u id
followee\u id
followee\u id
集合不能包含重复项(即,您不能跟踪一个人两次),它没有说明
followee\u id
followee\u id
不同

如果你想禁止跟随自己,那么你必须这样说:

  validate :cant_follow_yourself

private

  def cant_follow_yourself
    return if followee_id != follower_id
    # add an appropriate error message here...
  end
validates :follower_id, uniqueness: { scope: :followee_id }
  validate :cant_follow_yourself

private

  def cant_follow_yourself
    return if followee_id != follower_id
    # add an appropriate error message here...
  end