[英]How do you check whether or not a database contains a value in Ruby on Rails?
Quick question. 快速提问。
I'm wrapping up my RoR program and I'm trying to finish up user-proofing it. 我正在包装我的RoR程序,并试图完成对用户的验证。 I'll give a quick run down of what I'm trying to do: 我将简要介绍我要做的事情:
My program uses an HTML file that has a textfield for user input. 我的程序使用一个HTML文件,该文件具有用于用户输入的文本字段。 The textfield input, customerId is supposed to be an integer. 文本字段输入customerId应该是整数。 Anyways, I'm supposed to display a specific message if the input is invalid (validity based on specifications provided). 无论如何,如果输入无效(根据提供的规范有效),我应该显示一条特定的消息。 I used this line to verify that the input customerId is an int: 我使用此行来验证输入的customerId是否为int:
<% if @customerId =~ /\D/
render :action => 'invalid'
end %>
I'd like to put another if statement either in that or right after that.. that checks if the customer_Id value entered by the user is in the Customer table in the database. 我想在其中或之后放置另一个if语句,以检查用户输入的customer_Id值是否在数据库的Customer表中。
Is there an easy way of doing this? 有一个简单的方法吗? Logically I think it would be something like: 从逻辑上讲,我认为它将是这样的:
<% if !Customer.find(@customer_Id)
#customer not found message
end %>
This is the first project i've done using RoR and don't know of an easy implementation that Ruby provides for this. 这是我使用RoR完成的第一个项目,并且不知道Ruby为此提供了一个简单的实现。 Thanks! 谢谢!
To do this, I added some lines of code and instead of doing this in the view, I did it in the main controller. 为此,我添加了一些代码行,而不是在视图中这样做,而是在主控制器中完成。 Here's the block that did it: 这是执行此操作的块:
when "cu" then # customer data request
# Verify that customer is in the customer table
if Customer.exists?(@data)
# exists, display custdisply.html.erb
render :action => 'custdisplay'
else
# does not, display notfound.html.erb
render :action => 'notfound'
end
The Rails ActiveRecord library provides a lot of really nice validators which would seem appropriate in this case. Rails ActiveRecord库提供了许多非常不错的验证器 ,在这种情况下似乎很合适。
class Customer < ActiveRecord::Base
validates_presence_of :name
end
However, in this case, a validator is not necessary. 但是,在这种情况下,不需要验证器。 By default, when you call .find
on the model class, if the ID is invalid, it will raise an ActiveRecord::RecordNotFound
error and route to your public/404.html
page: 默认情况下,当您在模型类上调用.find
时,如果ID无效,则会引发ActiveRecord::RecordNotFound
错误并路由到您的public/404.html
页面:
class CustomersController < ApplicationController
def show
@customer = Customer.find(params[:id])
end
end
If you try calling .find
in a view script, it's too late because the routing has finished. 如果尝试在视图脚本中调用.find
,为时已晚,因为路由已完成。 You should be calling .find
in your controller. 您应该在控制器中调用.find
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.