使用 Rails 3 验证数据库中是否存在匹配条目
我需要一些帮助来解决以下问题。我想在我的视图中实现一个文本字段,并使用一个按钮检查数据库字段中是否有匹配的字符串。
更具体地说,我有一个带有电子邮件字段的帐户表。我想比较所有帐户的文本字段中的用户输入,如果有匹配的电子邮件,则返回 true
,如果电子邮件不匹配,则返回 false
。
有没有快速的方法来做到这一点?我对 Rails 很陌生,到目前为止,我所拥有的只是视图的以下代码:
= text_field_tag :search
= submit_tag "Check Email", :class => "submit"
我不确定要在模型或控制器中放入什么,但我已经编写了以下代码并将其放入帐户中。 rb 模型:
def email_exists?(search)
return true if account.where(:email => "%#{search}%").exists?
end
任何帮助将不胜感激。
I need some help with the following problem. I would like to implement a text field into my view with a button that checks for an matching string in a database field.
More specifically, I have an accounts table with an email field. I would like to compare the user input in the textfield across all accounts and return true
if there is a matching email, and false
if the email does not match.
Is there a quick way to do this? I'm very new to rails, and thus far, all I have is the following code for the view:
= text_field_tag :search
= submit_tag "Check Email", :class => "submit"
Im not exactly sure what to put in the model or the controller, but I have written the following code and placed it in accounts.rb model:
def email_exists?(search)
return true if account.where(:email => "%#{search}%").exists?
end
any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与模型通信的唯一方法是通过控制器操作。
访问控制器操作的唯一方法是通过资源上的 http 请求。
因此:
请注意,如果您向控制器询问某些内容,则需要呈现对此的 html 响应。
我猜您只是想通知用户电子邮件是否可用。为此,您需要发出 AJAX 请求。适用相同的步骤。
The only way to comunicate to your model is through controller actions.
The only way to access the controller actions is via http requests on your resources.
So:
Note that if you ask the controller something, you will need to render the html response to this.
Im guessing you just want to notify the user if the email is available. To do this you will need to make an AJAX request. The same steps apply.
您可能想要使用 Account.find_by_email 而不是手动完成这一切,并返回空的结果?方法。
也就是说,如果这是验证过程的一部分,则有多种方法可以实现——任何 Rails 教程都会有足够的信息来帮助您入门,并且您可能能够摆脱其默认值而不是编写您自己的代码(考虑 validates_uniqueness_of,但有一些注意事项)。
You'll probably want to use Account.find_by_email rather than doing it all manually, and return the results of the empty? method.
That said, if this is part of a validation process, there are a number of ways to go about it--any Rails tutorial will have enough info to get you started, and you may be able to get away with its defaults rather than writing your own code (think validates_uniqueness_of, with some caveats).