使用find_by方法检索多个记录

时间:2015-12-26 11:56:20

标签: ruby-on-rails ruby ruby-on-rails-4 methods controller

以下方法适用于对通过电子邮件发送令牌链接的用户进行身份验证。

def login
  inv = Invitation.find_by(email: params[:email])
  if inv && inv.authenticated?(:invitation, params[:id])
    @organization = inv.organization
    unless @organization.nil?
      render 'profiles/show' and return
    else
      flash[:danger] = "Error"
      redirect_to root_path
    end
  else
    flash[:danger] = "Invalid link"
    redirect_to root_path
  end
end

然而,此方法似乎假设某人(inv)只能在Invitation数据库中存在一次。情况并非如此,同一个人/电子邮件地址可以在数据库中有多个记录。因此,我需要重写方法来解决这种情况。我怎样才能做到这一点?我可以使用下面第2行添加的.all,并使用.each

def login
  inv = Invitation.find_by(email: params[:email]).all
  if inv
    inv.each do |person|
      if person.authenticated?(:invitation, params[:id])
        @organization = person.organization
        unless @organization.nil?
          render 'profiles/show' and return
        else
          flash[:danger] = "Error"
          redirect_to root_path and return
        end
      end
      flash[:danger] = "Invalid link"
      redirect_to root_path
    end
  else
    flash[:danger] = "Invalid link"
    redirect_to root_path
  end
end

错误讯息:

此代码会在下面生成错误消息,但我不确定除了.all之外还有什么用处:

NoMethodError: undefined method `all' for #<Invitation:0x0000000b869ee8>

1 个答案:

答案 0 :(得分:1)

您需要使用find_all_bywhere

inv = Invitation.find_all_by(email: params[:email])

inv = Invitation.where(email: params[:email])