【问题标题】:Retrieve multiple records with find_by method使用 find_by 方法检索多条记录
【发布时间】:2016-03-31 23:30:59
【问题描述】:

以下方法有效并验证已通过电子邮件发送令牌链接的用户。

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>

【问题讨论】:

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


    【解决方案1】:

    您需要使用find_all_bywhere

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

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

    【讨论】:

    • 谢谢!使用inv = Invitation.where('email = ?', params[:email]) 似乎让我更进一步。测试现在产生错误:ActionView::MissingTemplate: Missing template invitations/login。这样的视图确实不存在,但考虑到方法它不应该需要这样的视图。毕竟它总是指向rootprofiles/show。旧情况下测试通过,如下:get login_path('invalid token')(login_path 路由到控制器方法)。知道原因吗?
    猜你喜欢
    • 1970-01-01
    • 2021-03-04
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    相关资源
    最近更新 更多