字符串插值在 Sinatra 重定向中不起作用
String interpolation not working in Sinatra redirect
当我使用这个方法时:
patch '/posts/:id' do
post = Post.find(params[:id])
post.update(name: params[:name], content: params[:content])
redirect to '/posts/#{post.id}'
end
我收到错误 ERROR URI::InvalidURIError: bad URI(is not URI?): http://localhost:9393/posts/#{post.id}
但是当我硬编码 id 或像这样连接字符串时:
redirect to '/posts/' + post.id.to_s
它工作正常。我是否漏掉了一些明显的东西?
在 ruby 中,单引号 中声明的字符串文字不会被插入 ,这与双引号文字不同:
"#{42}"
#⇒ "42"
'#{42}'
#⇒ "\#{42}"
因此,只需将参数中的单引号更改为双引号即可 redirect to
。
当我使用这个方法时:
patch '/posts/:id' do
post = Post.find(params[:id])
post.update(name: params[:name], content: params[:content])
redirect to '/posts/#{post.id}'
end
我收到错误 ERROR URI::InvalidURIError: bad URI(is not URI?): http://localhost:9393/posts/#{post.id}
但是当我硬编码 id 或像这样连接字符串时:
redirect to '/posts/' + post.id.to_s
它工作正常。我是否漏掉了一些明显的东西?
在 ruby 中,单引号 中声明的字符串文字不会被插入 ,这与双引号文字不同:
"#{42}"
#⇒ "42"
'#{42}'
#⇒ "\#{42}"
因此,只需将参数中的单引号更改为双引号即可 redirect to
。