rails中的交叉唯一性模型validation
我有一个模型,我希望列包含不同的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 `#.invalid?` to return true, got false # ./spec/models/follow_spec.rb:23:in `block (2 levels) in '
从我读过的所有内容来看,这看起来都是写的。 任何人有任何指针?
谢谢
这个validation:
validates :follower_id, uniqueness: { scope: :followee_id }
简单地说每个followee_id
的follower_id
集合不能包含重复项(即你不能跟随一个人两次),它没有说followee_id
与follower_id
不同。
如果你想禁止跟随自己,那么你必须这样说:
validate :cant_follow_yourself private def cant_follow_yourself return if followee_id != follower_id # add an appropriate error message here... end