使用find_by方法检索多个记录 [英] Retrieve multiple records with find_by method
问题描述
以下方法适用于通过电子邮件发送了令牌链接的用户。
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
这个方法似乎假设一个人( inv
)只能存在一次在 Invitation
数据库。这不是这种情况,同一个人/电子邮件地址可以在数据库中有多个记录。因此,我需要重写方法来解释这种情况。我如何做到这一点?我可以使用 .all
在下面第2行中添加,并使用 .each
?
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
错误讯息:
此代码产生以下错误讯息,但我不确定 .all
使用:
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>
推荐答案
您需要使用 find_all_by
或其中
inv = Invitation.find_all_by(email: params[:email])
或
inv = Invitation.where(email: params[:email])
这篇关于使用find_by方法检索多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!