Sinatra将params [:id]匹配为字符串类型,是否需要其他转换以匹配数据库ID? [英] Sinatra matches params[:id] as string type, additional conversion needed to match the database id?

查看:96
本文介绍了Sinatra将params [:id]匹配为字符串类型,是否需要其他转换以匹配数据库ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用sinatra和DataMapper访问sqlite3数据库。调用 get(params [:id])时,总是得到 nil 。但是当我调用 get(params [:id] .to_i)时,我可以获得正确的记录。

I am using sinatra and DataMapper to access an sqlite3 database. I always get an nil when calling get(params[:id]). But when I call get(params[:id].to_i) I can get the right record. Is there anything wrong such that I have to do the conversion explicitly?

sinatra应用程序很简单:

The sinatra app is simple:

class Record
  include DataMapper::Resource
  property :id, Serial
  ....
end

get '/list/:id' do
  r = Record.get(params[:id])
  ...
end


推荐答案

显然这是Datamapper的问题(如果您认为它应该将字符串转换为ID的数字),但是有Sinatra减轻它的方式。当出现参数时,您需要检查:

Obviously this is a problem with Datamapper (if you believe it should be casting strings to numbers for id's), but there are ways Sinatra can mitigate it. When params come in you need to check:


  • 它们存在。

  • 它们是正确的类型(或可铸造)。

  • 它们在所需或期望的值范围内。

例如:

get '/list/:id' do
  r = Record.get(params[:id].to_i)
  # more code…


curl http://example.org/list/ddd

效果不好,最好检查并返回错误消息:

That won't work well, better to check and return an error message:

get '/list/:id' do |id| # the block syntax is helpful here
  halt 400, "Supply an I.D. *number*" unless id =~ /\d+/

然后考虑是否要使用默认值值是否在正确的范围内等。在获取ID时,我倾向于使用路由的正则表达式语法,因为它也停止跟踪子路由,同时提供了一点简单的类型检查:

Then consider whether you want a default value, whether the value is in the right range etc. When taking in ID's I tend to use the regex syntax for routes, as it stops following sub routes being gobbled up too, while providing a bit of easy type checking:

get %r{/list/(\d+)} do |id|

在这种情况下,助手也很有用:

Helpers are also useful in this situation:

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)

这篇关于Sinatra将params [:id]匹配为字符串类型,是否需要其他转换以匹配数据库ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆