使用1个值搜索两个不同的字段

时间:2015-02-02 18:09:07

标签: ruby-on-rails ruby-on-rails-4 activerecord

在数据库中,我有2个不同的令牌用于不同的集成。如果指定了集成代码,我想识别用户。集成令牌是唯一的,但每个用户记录只需要2个令牌。

最简单的方法是传递额外的参数,但是我必须与一些我无法修改的遗留应用程序集成。

到目前为止,我已经写过类似的内容,但我相信有更干净,更“顽固”的方式来获得相同的结果。 你能帮帮我吗?

def user
  target_user = nil

  target_user = User.where.not(user_token_type1: nil)
      .find_by(user_token_type1: params[:user_token])

  target_user = User.where.not(user_token_type2: nil)
      .find_by(user_token_type2: params[:user_token]) if target_user.blank?

  target_user || user_not_found
end

2 个答案:

答案 0 :(得分:0)

if val = params[:user_token].presence
  query = "user_token_type1 = :token OR user_token_type2 = :token"
  User.where(query, {token: val}).last
end || user_not_found

我读了你的评论,如果你必须,你也可以这样做:

val = params[:token_val]

User.where.not(user_token_type1: nil).find_by(user_token_type1: val) || \
User.where.not(user_token_type2: nil).find_by(user_token_type2: val)

但这显然会导致两个查询,其中一个人可以完美地完成工作。

答案 1 :(得分:0)

您也可以这样做:

User.where("user_token_type1 = ? OR user_token_type2 = ?", params[:user_token], params[:user_token])

另外,请删除User.where.not(user_token_type1: nil)。向模型添加约束,以便您可以信任您的数据,而不是添加该样板。