ruby-on-rails – Rails 3.0:在模型中覆盖to_param时出现路径错误

当我尝试在我的用户模型中覆盖to_param以使用电子邮件地址作为id时,我的路由出错了.它似乎试图在尝试匹配路由时匹配id的整个对象.任何人都可以帮我弄清楚我错过了什么?

这是错误:

No route matches {:controller=>"users",:action=>"show",:id=>#<User id: 1,email: ....>}

这是我如何设置代码.

车型/ user.rb:

attr_accessible :email    

def to_param 
  email
end

控制器/ users_controller.rb:

before_filter :get_user,:only=>[:show,:update,:edit,:destroy]

...

def get_user
  @user = User.find_by_email params[:id]
end

配置/ routes.rb中

resources :users

这是rake路线的输出:

user GET    /users(.:format)          {:controller=>"users",:action=>"index"}
          POST   /users(.:format)          {:controller=>"users",:action=>"create"}
 new_user GET    /users/new(.:format)      {:controller=>"users",:action=>"new"}
edit_user GET    /users/:id/edit(.:format) {:controller=>"users",:action=>"edit"}
     user GET    /users/:id(.:format)      {:controller=>"users",:action=>"show"}
          PUT    /users/:id(.:format)      {:controller=>"users",:action=>"update"}
          DELETE /users/:id(.:format)      {:controller=>"users",:action=>"destroy"}

解决方法

问题是电子邮件添加了’.’ (点)在网址中,这会混淆rails,因为它试图找到“com”格式(如果电子邮件以.com结尾)

我已将此代码添加到我的某个应用程序(我有人而不是用户)并且它正常工作,所以诀窍是用其他东西替换点.我选择将其替换为“@”作为其他符号,例如 – 或在电子邮件地址中有效.

档案人.rb

def to_param
  email.sub ".","@"
end

def self.param_to_email(param) 
  segments = param.split '@'
  host = segments[1..-1].join('.')
  segments[0] + '@' + host
end

文件people_controller.rb

def get_person
  email = Person.param_to_email params[:id]
  @person = Person.find_by_email email
end

关于这在http://jroller.com/obie/entry/seo_optimization_of_urls_in中是如何工作的还有一些提示.

谢谢你的问题,我刚开始使用rails,所以这真的帮助我理解它是如何工作的:).

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...