Ruby on rails 从链接中提取参数值,Rails 4

Ruby on rails 从链接中提取参数值,Rails 4,ruby-on-rails,Ruby On Rails,我有这样的链接: http://localhost:3000/sms/receive/sms-id=7bb28e244189f2cf36cbebb9d1d4d02001da53ab&operator-%20id=1&from=37126300682&to=371144&text=RV9+c+Dace+Reituma+0580913 我想从这个链接中提取所有不同的变量值。例如sms id、操作员、发件人、收件人和文本 到目前为止,我一直是这样的: http://l

我有这样的链接:

http://localhost:3000/sms/receive/sms-id=7bb28e244189f2cf36cbebb9d1d4d02001da53ab&operator-%20id=1&from=37126300682&to=371144&text=RV9+c+Dace+Reituma+0580913
我想从这个链接中提取所有不同的变量值。例如sms id、操作员、发件人、收件人和文本

到目前为止,我一直是这样的:

http://localhost:3000/sms/receive/sms-id=7bb28e244189f2cf36cbebb9d1d4d02001da53ab&operator-%20id=1&from=37126300682&to=371144&text=RV9+c+Dace+Reituma+0580913
routes.rb

get 'sms/receive/:params', to: 'sms#receive'
SMS#接收控制器

def receive

     query = params[:params]

      sms_id=     query[/["="].+?[&]/]   

      flash[:notice] = sms_id

end
这给了我:
=7bb28e244189f2cf36cbebb9d1d4d02001da53ab&
,但我需要不带第一个=和最后一个字符

如果我尝试添加一些字符串,比如:
query[/[“sms id”].+?[&operator]/]
,这样可以让我顺利提取所有变量,它会给我错误:
char类中的空范围:/[“sms id”].+?[&operator]/

但我相信还有其他方法可以以不同的方式提取所有这些变量值

提前谢谢

你需要

get 'sms/receive/', to: 'sms#receive' 
routes.rb中的路径,并在控制器中获取
params

matches = params[:params].scan(/(?:=)([\w\+]+)(?:\&)?/)
# this will make matches = [[first_match], [second_match], ..., [nth_match]]

# now you can read all matches

sms_id = matches[0][0]
operator_id = matches[1][0]
from = matches[2][0]
to = matches[3][0]
text = matches[4][0]
# and it will not contatin = or &

我建议您在model或helper中创建方法,而不要在controller中编写整个代码。

正则表达式中的错误是因为
-
在方括号中是保留字符。在此上下文中,必须使用反斜杠对其进行转义:
\-

要分析查询字符串,可以执行以下操作:

sms_id = params[:params].match(/sms-id=([^&]*)/)[1]
或者使用更通用的方法对其进行分析:

parsed_query = Rack::Utils.parse_nested_query(params[:params])
sms_id = parsed_query['sms-id']
(引自)

如果您可以控制初始URL,请将最后一个
/
更改为
,以获得更简单的解决方案:

http://localhost:3000/sms/receive?sms-id=7bb28e244189f2cf36cbebb9d1d4d02001da53ab&operator-%20id=1&from=37126300682&to=371144&text=RV9+c+Dace+Reituma+0580913
您将在
params
中拥有
sms id

sms_id = params['sms-id']

这给了我
没有路由匹配[GET]“/sms/receive/sms id=7bb28e244189f2cf36cbebb9d1d4d02001da53ab&operator-%20id=1&from=37126300682&to=371144&text=RV9+c+Dace+Reituma+0580913”
我以前试过这个方法……你能把url改成正确的语法:“/sms/receive?sms id=7BB28E244189F2CF36CBEB9D1D42001DA53AB&operator-%20id=1&f吗‌​rom=37126300682&to=371144&text=RV9+c+Dace+Reituma+0580913“(添加?而不是/在参数之前)?很好,我现在理解我的问题了。我可以访问除sms id和operator id之外的所有参数,因为中间的那一行应该是下划线?应该注意查询字符串(在
之后的内容)不是路由的一部分,不应该在那里提及。看起来不错,但当我尝试时,我得到了错误
未定义的方法
scan'`什么类型是
params[:params]
最后一句话救了我的命,必须是这样:)