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

时间:2014-07-04 02:29:53

标签: 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

模型

class Follow < ActiveRecord::Base
  belongs_to :follower, class_name: 'User'
  belongs_to :followee, class_name: 'User'

  validates :follower_id, uniqueness: { scope: :followee_id }
end

但我的测试似乎失败了

测试

it 'cannot follow itself' do
  user = FactoryGirl.create(:user)
  follow = FactoryGirl.create(:follow, follower: user, followee: user)
  expect(follow).to be_invalid
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 个答案:

答案 0 :(得分:1)

此验证:

validates :follower_id, uniqueness: { scope: :followee_id }

简单地说每个follower_id的{​​{1}} s集合不能包含重复项(即您不能跟随一个人两次),它没有说明followee_id不同来自followee_id

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

follower_id