Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 传递两个参数以使其存在?在轨_Ruby On Rails_Ruby_Validation_Activerecord - Fatal编程技术网

Ruby on rails 传递两个参数以使其存在?在轨

Ruby on rails 传递两个参数以使其存在?在轨,ruby-on-rails,ruby,validation,activerecord,Ruby On Rails,Ruby,Validation,Activerecord,我有一个friendships模型,friendships是一个包含用户ida朋友id和状态(一个字符串)的联接表。在友谊的创建方法中,我需要进行一些验证,并检查该用户和该朋友之间是否已经存在友谊。为此,我调用了: unless userID == friendID or Friendship.exists?(userID, friendID) 然而存在?调用create时引发此错误: ArgumentError (wrong number of arguments (2 for 0..1))

我有一个friendships模型,friendships是一个包含
用户id
a
朋友id
和状态(一个字符串)的联接表。在友谊的创建方法中,我需要进行一些验证,并检查该用户和该
朋友之间是否已经存在友谊。为此,我调用了:

unless userID == friendID or Friendship.exists?(userID, friendID)
然而存在?调用create时引发此错误:

ArgumentError (wrong number of arguments (2 for 0..1)):
如果不检查一个友谊中是否存在
userID
friendID
,我就无法正确地进行验证。我的问题是,有没有更好的方法可以做到这一点?或者,是否有一种方法可以将两个参数传递给exists?方法

谢谢你的帮助和建议

@userid = any_user_id
@friendid = any_friend_id
(@userid == @friendid || Friendship.where(user_id: @userid,friend_id: @friendid).present?) ? true : false
或者如果您想使用
存在?

(@userid == @friendid || Friendship.exists?(user_id: @userid,friend_id: @friendid)) ? true : false
这正是你所需要的

您可以使用来执行此操作

class Friendship < ActiveRecord::Base
  # ensure that user/friend combo does not already exist
  validates :user, uniqueness: { scope: friend }

  # ensure that friend != user
  validate :friend_is_not_user

  # other Friendship model code

  def friend_is_not_user
    if self.friend == self.user
      errors.add(:user, 'cannot be friends with his or her self.')
    end
  end
end
类友谊
难道不是吗?真:假`在这里是多余的吗<代码>存在?
返回已存在的
true
false
。与
present?
相同。但是您有带另一个条件的“| |”,可能这个条件将返回false,也将返回
友谊。存在?(用户id:@userid,朋友id:@friendid)
将返回false这不是1个条件。