我已在我的应用中成功实施了邀请功能。每个用户都有很多记分牌,每个记分牌都有很多邀请。邀请模型有两列,即recipient_name和recipient_email,并且会向recipient_email发送邀请电子邮件。所有这些功能都完美无缺。下面给出了创建操作的控制器代码。
** 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
作为该功能的扩展,我还想查询数据库以检查邀请模型中提供的recipient_email是否存在于用户模型中(column:email)。当用户注册时,我将电子邮件设置为唯一,因此,搜索电子邮件将显示用户是否已注册。
问题是我不知道如何检查invitation_table中是否存在invitation_table中的recipient_email。我尝试过几件事。 我尝试将recipient_email的最新记录保存在本地变量中,然后查询数据库中的该记录。我并不认为这是实现这一目标的正确方法。
我还在邀请函的新操作中使用简单的if和else语句测试了下面给出的代码,看看会发生什么。但是,每当我向注册用户或未注册用户发送电子邮件时,它始终打印" no"。我不确定如何正确处理这个问题。我知道存在吗?方法将在某处使用但不确定如何真正使用它。我试图保持它的重点,并包括相关的代码片段。但是,如果我错过任何东西,我肯定可以包括那些。任何帮助将不胜感激,谢谢!!
<% if User.where("email = ?", @invitation.recipient_email).exists? %>
<%= "Yes" %>
<% else %>
<%= "no" %>
<% end %>
答案 0 :(得分:2)
您使用.exists了吗?方法,但你实际上是错误地调用它。条件(你有一个.where语句)实际上是要传递给.exists?作为参数发挥作用。
所以,而不是说:
if User.where("email = ?", @invitation.recipient_email).exists?
你其实想说:
if User.exists?( email: @invitation.recipient_email )
.exists?获取与值配对的字段名称的哈希值。有关存在的更多细节?方法,see the official documentation。
<强>附录强>
关于散列表示法(传递给.exists?方法),在最新版本的Rails中,&#34;标准&#34;将参数传递给ActiveRecord方法的方式是哈希形式。但是,有时候使用您选择使用的问号插值方法是合适的。我只提供此评论以减轻两种不同方法调用之间的任何混淆。以下各项都将执行相同的查询:
.where("field = ?", value)
.where(:field => value)
.where(field: value)