ruby-on-rails – Rails REST路由:资源项ID中的点

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails REST路由:资源项ID中的点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的路线中有以下内容
  1. resources :users,:except => [:new,:create] do
  2. get 'friends',:as => :friends,:on => :member,:to => "users#friends"
  3. end

并在我的user.rb中:

  1. def to_param
  2. self.login
  3. end

例如,当登录时使用点(例如“any.thing”)的用户来自facebook时,rails会给出路由错误(找不到路由,因为它可以识别点之后的任何内容,或者因为路由约束).我怎么能想到这个错误

解决方法

您可以用另一个字符替换句点:
  1. def to_param
  2. login.gsub(/\./,"-") # note: 'self' is not needed here
  3. end
  4.  
  5. user = User.find_by_login("bart.simpson")
  6. user_path(user) # => "/users/bart-simpson"

编辑

你是对的,这不能处理映射到相同值的唯一登录.也许更好的方法是在路由中使用段约束:

  1. match 'users/(:id)' => 'users#show',:constraints => { :id => /[0-9A-Za-z\-\.]+/ }

这应该允许“/ users / bart-simpson”和/users/bart.simpson“分别生成:id ="”bart-simpson“和:id ="”bart.simpson“你必须改变正则表达式添加URL的所有可接受的字符.

请注意,这在Rails Routing Guide第3.2节中提到:

By default dynamic segments don’t accept dots – this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment add a constraint which overrides this – for example :id => /[^/]+/ allows anything except a slash.

猜你在找的Ruby相关文章