【问题标题】:passing two parameters to exist? in rails传递两个参数存在?在铁轨上
【发布时间】:2014-05-25 17:09:19
【问题描述】:

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

unless userID == friendID or Friendship.exists?(userID, friendID)

然而存在吗?调用 create 时抛出此错误:

ArgumentError (wrong number of arguments (2 for 0..1)):

如果不检查userIDfriendID 是否存在于一个友谊中,我将无法正确进行验证。我的问题是有没有更好的方法可以做到这一点而不使用存在?或者有没有办法可以将两个参数传递给存在?轨道中的方法。

感谢您的任何帮助或建议。

【问题讨论】:

    标签: ruby-on-rails ruby validation activerecord


    【解决方案1】:
    @userid = any_user_id
    @friendid = any_friend_id
    (@userid == @friendid || Friendship.where(user_id: @userid,friend_id: @friendid).present?) ? true : false
    

    或者如果你想使用exists?

    (@userid == @friendid || Friendship.exists?(user_id: @userid,friend_id: @friendid)) ? true : false
    

    这将完全满足您的需求。

    【讨论】:

    • 不会是 ` 吗? true : false` 在这里会是多余的吗? exists? 已经返回 truefalse。与present? 相同。
    • 但是你有'||'在另一个条件下,这个条件可能会返回 false,Friendship.exists?(user_id: @userid,friend_id: @friendid) 也会返回 false 这不是 1 个条件。
    【解决方案2】:

    您可以使用rails validation methods 来执行此操作。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 2013-05-03
      • 2011-02-19
      • 2011-12-06
      • 2016-09-25
      相关资源
      最近更新 更多