Rails中的交叉唯一性模型验证 [英] Cross uniqueness model validation in rails
本文介绍了Rails中的交叉唯一性模型验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模型,希望列包含不同的ID.因此,一个用户可以关注另一个用户,但不能关注自己.
I have a model where I want columns to contain different ids. So a user may follow another user, but not follow themselves.
迁移
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)>'
从我读过的所有内容来看,这看起来像是在写.有人有指针吗?
From everything I've read, this looks write. Anyone have any pointers?
谢谢
推荐答案
此验证:
validates :follower_id, uniqueness: { scope: :followee_id }
简单地说,每个followee_id
的follower_id
集合不能包含重复项(即,您不能跟随一个人两次),它并没有说明followee_id
与follower_id
不同.
simply says that the set of follower_id
s for each followee_id
cannot contain duplicates (i.e. you can't follow one person twice), it says nothing about followee_id
being different from follower_id
.
如果您想禁止自己跟随自己,则必须这样说:
If you want to disallow following yourself then you have to say so:
validate :cant_follow_yourself
private
def cant_follow_yourself
return if followee_id != follower_id
# add an appropriate error message here...
end
这篇关于Rails中的交叉唯一性模型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文