2016-02-04 41 views
0

我已安装friendly_id gem(版本5.1.0),并已在文档中实现了扩展我的模型,将slug字段添加到表等内容中的步骤。预期:通过电子邮件地址找到URL不与FriendlyId一起使用

http://localhost:3000/owners/1 

我试图通过电子邮件地址找到,但怎么看怎么尾随.com是正在接受治疗:

http://localhost:3000/owners/[email protected] 

{"id"=>"[email protected]", 
"format"=>"com"} 

而且因为我的客户是真正希望得到的结果找到json格式,客户端应该发送这个URL到服务器:

http://localhost:3000/[email protected] 

但Rails没有这样的:

No route matches [GET] "/owners/[email protected]" 

其中作为

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

返回预期的JSON视图。

我应该怎样编码才能解决这个问题?

回答

0

其实这不是一个friendly_id问题。您的控制器根本不会被调用,因为您的网址(/owners/[email protected]/[email protected])不符合您在config/routes.rb中的任何路线。

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

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

和控制器:

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/[email protected] 

结果:

{"hello":"[email protected]"} 
+0

确切的设置工作,所以我接受了回答并表达我的谢意,感谢您给予的帮助。当我尝试让这个动作被我的所有者控制器捕获时,Rails深入到超类中,而不是查找params [:email]它查找params [:id],所以我会继续玩这个。 – tobinjim

+0

我的不好:我不得不改变路线获得“所有者/:电子邮件”等,而不是只得到“/:电子邮件”---非常感谢! – tobinjim

+0

@tobinjim,您随时欢迎;-) – kimrgrey