URL 通过电子邮件地址查找不适用于 FriendlyId

URL finding by email address not working with FriendlyId

我安装了 friendly_id gem(版本 5.1.0)并实施了文档中的步骤来扩展我的模型,将 slug 字段添加到 table,等等。这个 url 按预期工作:

http://localhost:3000/owners/1

我正在尝试通过电子邮件地址查找,但请查看尾随的 .com 是如何处理的:

http://localhost:3000/owners/me@example.com

{"id"=>"me@example",
 "format"=>"com"}

并且由于我的客户端确实希望以 json 格式接收查找结果,因此客户端应该将此 URL 发送到服务器:

http://localhost:3000/me@example.com.json

但 Rails 不喜欢这样:

No route matches [GET] "/owners/me@example.com.json"

其中

http://localhost:3000/owners/1.json

returns json 视图符合预期。

我应该如何(或什么)编码来解决这个问题?

实际上,这不是 friendly_id 问题。您的控制器根本没有被调用,因为您有一个 URL (/owners/me@example.com/me@example.com) 不满足 config/routes.rb 中的任何路由。

这是因为路径末尾有“.com”。您应该添加一个约束来告诉 Rails 您将收到一封电子邮件作为 url 的一部分。我创建了一个具有以下路由的小项目:

get "/:email", :to => "application#test", :constraints => { :email => /.+@.+\..*/ }

和控制器:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  def test
    respond_to do |format|
      format.any { render :json => { :hello => params[:email] } }
    end
  end
end

然后我可以使用 curl:

调用它
curl -H "Accept: application/json" http://localhost:3000/boo@example.com

结果:

{"hello":"boo@example.com"}