我的路线中有以下内容:
resources :users,:except => [:new,:create] do get 'friends',:as => :friends,:on => :member,:to => "users#friends" end
并在我的user.rb中:
def to_param self.login end
例如,当登录时使用点(例如“any.thing”)的用户来自facebook时,rails会给出路由错误(找不到路由,因为它可以识别点之后的任何内容,或者因为路由约束).我怎么能想到这个错误?
解决方法
您可以用另一个字符替换句点:
def to_param login.gsub(/\./,"-") # note: 'self' is not needed here end user = User.find_by_login("bart.simpson") user_path(user) # => "/users/bart-simpson"
编辑
你是对的,这不能处理映射到相同值的唯一登录.也许更好的方法是在路由中使用段约束:
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.