Retrieve multiple records with find_by method

2019-08-19 07:13发布

问题:

The method below works and authenticates a user who has been sent a token-link by email.

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

This method however seems to assume a person (inv) can only exist once in the Invitation database. This is not the case, the same person/email address can have multiple records in the database. Therefore, I need to rewrite the method to account for such a situation. How can I do this? Can I use .all as added on line 2 below, and use .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

Error messages:

This code produces the error message below but I'm not sure what else than .all to use:

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

回答1:

You need to use find_all_by or where

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

or

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