【问题标题】:Cross uniqueness model validation in railsrails中的交叉唯一性模型验证
【发布时间】:2014-07-04 02:29:53
【问题描述】:

我有一个模型,我希望列包含不同的 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)>'

从我读过的所有内容来看,这看起来是写的。有人有任何指示吗?

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby validation activerecord models


    【解决方案1】:

    此验证:

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

    只是说每个followee_idfollower_ids 集合不能包含重复项(即你不能关注一个人两次),它没有说明followee_idfollower_id 不同。

    如果您想禁止关注自己,那么您必须这样说:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 2023-03-07
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      相关资源
      最近更新 更多