Retrieve multiple records with find_by method

我怕爱的太早我们不能终老 提交于 2020-01-06 14:49:10

问题


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])


来源:https://stackoverflow.com/questions/34471108/retrieve-multiple-records-with-find-by-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!