Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 查询数据库以检查邀请模型中提供的电子邮件是否已存在于用户模型中_Ruby On Rails_Email - Fatal编程技术网

Ruby on rails 查询数据库以检查邀请模型中提供的电子邮件是否已存在于用户模型中

Ruby on rails 查询数据库以检查邀请模型中提供的电子邮件是否已存在于用户模型中,ruby-on-rails,email,Ruby On Rails,Email,我已成功在我的应用程序中实现了邀请功能。每个用户都有很多记分牌,每个记分牌都有很多邀请。邀请模型有两列,收件人名称和收件人电子邮件,邀请电子邮件发送到收件人电子邮件。所有这些功能都工作得非常好。创建操作的控制器代码如下所示 ** scoreboard ** has_many :sent_invitations, :class_name => "Invitation" def create @scoreboard = Scoreboard.find(params[:scoreboa

我已成功在我的应用程序中实现了邀请功能。每个用户都有很多记分牌,每个记分牌都有很多邀请。邀请模型有两列,收件人名称和收件人电子邮件,邀请电子邮件发送到收件人电子邮件。所有这些功能都工作得非常好。创建操作的控制器代码如下所示

** scoreboard 
** has_many :sent_invitations, :class_name => "Invitation"
def create
    @scoreboard = Scoreboard.find(params[:scoreboard_id])
    @invitation = @scoreboard.sent_invitations.build(invitation_params)
    if @invitation.save  # and the recipient_email doesn't exist in the user model database
                         # send the sign_up email
      UserMailer.invitation_email(@invitation, @scoreboard).deliver_now
      flash[:success] = "Invitation sent"
      redirect_to new_scoreboard_invitation_path

    #elsif
      # if the user exists in the database
      # send the email saying they've been invited to view a scoreboard

    else
      render new_scoreboard_invitation_path
    end
  end
end
作为该功能的扩展,我还想查询数据库,以检查邀请模型中提供的收件人电子邮件是否存在于用户模型中(列:email)。当用户注册时,我将电子邮件设置为唯一的,因此,搜索电子邮件将显示用户是否注册

问题是,我不确定如何检查“邀请”表中的收件人电子邮件是否也存在于“用户”表中。我试过几种方法。 我曾尝试将收件人的电子邮件的最新记录保存在局部变量中,然后在数据库中查询该记录。我认为这不是实现这一目标的正确方法

我还使用一个简单的if和else语句测试了下面邀请的新操作中给出的代码,以查看会发生什么。然而,每次我向注册或未注册的用户发送电子邮件时,它总是打印“否”。我不太清楚如何正确处理这个问题。我知道这个世界存在吗?方法将在某个地方使用,但不确定如何真正使用它。我已经尽力做到这一点,并包含了相关的代码片段。但是,如果我遗漏了什么,我肯定可以包括在内。任何帮助都将不胜感激,谢谢

   <% if User.where("email = ?", @invitation.recipient_email).exists? %>
    <%= "Yes" %>
   <% else %>
    <%= "no" %>
   <% end %>

您使用.exists的方法正确吗?方法,但实际上您没有正确调用它。条件(作为.where语句)实际上要传递给.exists?函数作为参数

因此,与其说:

if User.where("email = ?", @invitation.recipient_email).exists?
你真的想说:

if User.exists?( email: @invitation.recipient_email )
.存在吗?获取字段名与值的哈希值。要了解更多关于存在的问题的详细信息?方法

附录

关于散列表示法(传递给.exists?方法),在Rails的最新版本中,将参数传递给ActiveRecord方法的“标准”方式是散列形式。但是,在某些情况下,使用您选择使用的问号插值方法是合适的。我提供此评论只是为了缓解两个不同方法调用之间的任何混淆。以下各项将执行相同的查询:

.where("field = ?", value)
.where(:field => value)
.where(field: value)

谢谢你,这对我有用。我一定会仔细阅读文档。再次感谢。