在 Sinatra 中,我如何检查用户输入到表单中的术语是否已存在于您的数据库中?
How in Sinatra would I check that the term the user has input into a form already exists in your database?
在学习使用的同时制作预算应用 Ruby/Sinatra/SQL。其中一部分涉及让用户添加他们可以将交易分配给的新供应商。我的添加交易和添加供应商功能都有效,但我想做的一件事是能够在用户尝试添加供应商时抛出错误 - 例如 'Amazon' 已经在数据库中,在回到我的供应商索引之前。
我最接近的工作是使供应商的名称列 table 唯一。但是,如果我输入字段中已存在的名称,则会出现 "PG::UniqueViolation" 错误。
有没有办法告诉 Sinatra 您不想标记此错误,您只想重定向回没有重复值的供应商索引。
我的工作提交表单目前看起来像:
<div id="new-transaction">
<form action="/vendors/create" method="POST">
<label for="name">New vendor name:</label>
<input type="text" name="name" id="vendorName" />
<input type="submit" value="Add new vendor" id="btn-new-vendor">
</form>
</div>
继续使用该错误作为在您的应用中处理的响应。您可以在您的方法中添加一个 begin/rescue/end
块:
# some code before
begin
DB.add_your_vendor_method
rescue
go_back_to_index
end
show_value_to_user
# some code after
您也可以使该块错误具体化。在 http://rubylearning.com/satishtalim/ruby_exceptions.html
上有一些关于 ruby 错误处理的好文章
在学习使用的同时制作预算应用 Ruby/Sinatra/SQL。其中一部分涉及让用户添加他们可以将交易分配给的新供应商。我的添加交易和添加供应商功能都有效,但我想做的一件事是能够在用户尝试添加供应商时抛出错误 - 例如 'Amazon' 已经在数据库中,在回到我的供应商索引之前。
我最接近的工作是使供应商的名称列 table 唯一。但是,如果我输入字段中已存在的名称,则会出现 "PG::UniqueViolation" 错误。
有没有办法告诉 Sinatra 您不想标记此错误,您只想重定向回没有重复值的供应商索引。
我的工作提交表单目前看起来像:
<div id="new-transaction">
<form action="/vendors/create" method="POST">
<label for="name">New vendor name:</label>
<input type="text" name="name" id="vendorName" />
<input type="submit" value="Add new vendor" id="btn-new-vendor">
</form>
</div>
继续使用该错误作为在您的应用中处理的响应。您可以在您的方法中添加一个 begin/rescue/end
块:
# some code before
begin
DB.add_your_vendor_method
rescue
go_back_to_index
end
show_value_to_user
# some code after
您也可以使该块错误具体化。在 http://rubylearning.com/satishtalim/ruby_exceptions.html
上有一些关于 ruby 错误处理的好文章