Ruby Sinatra将params[:id]匹配为字符串类型,是否需要额外的转换来匹配数据库id?
我正在使用sinatra和DataMapper访问sqlite3数据库。调用Ruby Sinatra将params[:id]匹配为字符串类型,是否需要额外的转换来匹配数据库id?,ruby,sinatra,datamapper,Ruby,Sinatra,Datamapper,我正在使用sinatra和DataMapper访问sqlite3数据库。调用get(params[:id])时,我总是得到一个nil。但是当我调用get(params[:id].to_I)时,我可以得到正确的记录。是否有任何错误导致我必须显式地进行转换 sinatra应用程序很简单: class Record include DataMapper::Resource property :id, Serial .... end get '/list/:id' do r = Rec
get(params[:id])
时,我总是得到一个nil
。但是当我调用get(params[:id].to_I)
时,我可以得到正确的记录。是否有任何错误导致我必须显式地进行转换
sinatra应用程序很简单:
class Record
include DataMapper::Resource
property :id, Serial
....
end
get '/list/:id' do
r = Record.get(params[:id])
...
end
显然,这是Datamapper的一个问题(如果您认为它应该将字符串转换为id的数字),但Sinatra有一些方法可以缓解这个问题。当参数进入时,您需要检查:
- 它们是存在的
- 他们是正确的类型(或铸造)
- 它们在要求或预期的值范围内
get '/list/:id' do
r = Record.get(params[:id].to_i)
# more code…
curl http://example.org/list/ddd
这将无法正常工作,最好检查并返回错误消息:
get '/list/:id' do |id| # the block syntax is helpful here
halt 400, "Supply an I.D. *number*" unless id =~ /\d+/
然后,等等。当接收我倾向于使用的ID时,它会停止以下子路由被占用,同时提供一些简单的类型检查:
get %r{/list/(\d+)} do |id|
在这种情况下,助手也很有用:
helpers do
# it's not required to take an argument,
# the params helper is accessible inside other helpers
# it's but easier to test, and (perhaps) philosophically better.
def id( ps )
if ps[:id]
ps[:id].to_i
else
# raise an error, halt, or redirect, or whatever!
end
end
end
get '/list/:id' do
r = Record.get id(params)
为了澄清,@mbj在原始问题中的评论是正确的。这是Ruby 2.0的dm内核中的一个bug。它在ruby 1.9上运行良好。您可能使用的是dm core 1.2版,需要1.2.1版,您可以通过运行“gem update dm core”获得该版本。您是否受到此问题的影响?(使用ruby-2.0?@mbj,是的!同样的,ruby 2.0!嗨@iain,我完全同意手动将
转换为_I
从来都不是一个好主意。我没有太多考虑params[:id]的隐式转换,这是一个很好的主题,我会对其他框架如何处理您上面提到的三点做一些研究。感谢助手的良好实践
!