Rails REST 路由:资源项 ID 中的点 [英] Rails REST routing: dots in the resource item ID
问题描述
我的 routes.rb 中有以下内容:
I have following in my routes.rb:
resources :users, :except => [:new, :create] do
get 'friends', :as => :friends, :on => :member, :to => "users#friends"
end
并在我的 user.rb 中关注:
and following in my user.rb:
def to_param
self.login
end
例如,当用户登录时带有点(例如any.thing")来自 facebook,rails 会给出路由错误(未找到路由,我想这是因为它将点之后的任何内容识别为格式,或者因为路线限制).我怎样才能克服这个错误?
And when, for example, user with dots in login (for example 'any.thing') comes from facebook, rails gives routing error (no route found, I suppose that's because it recognises anything after dot as a format or because of route constraints). How can I come over this error?
推荐答案
您可以用另一个字符替换句点:
You could replace periods with another character:
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"
编辑
您说得对,这无法处理映射到相同值的唯一登录名.也许更好的方法是在路线中使用段约束:
You're right, this fails to deal with unique logins that map to the same value. Maybe a better way is to use segment constraints in the route:
match 'users/(:id)' => 'users#show',
:constraints => { :id => /[0-9A-Za-z\-\.]+/ }
这应该允许 "/users/bart-simpson"
和 /users/bart.simpson"
生成 :id => "bart-simpson"
和 :id => "bart.simpson"
分别.您必须更改正则表达式以添加 URL 的所有可接受字符.
This should allow "/users/bart-simpson"
and /users/bart.simpson"
to generate :id => "bart-simpson"
and :id => "bart.simpson"
respectively. You'd have to alter the regex to add all the acceptable characters for the URL.
请注意,Rails 路由指南,第 3.2 节中提到了这一点:
Note that this is mentioned in the Rails Routing Guide, section 3.2:
默认情况下,动态段不接受点——这是因为点用作格式化路由的分隔符.如果您需要使用一个动态段内的点添加一个约束来覆盖它 -例如 :id =>/[^\/]+/
允许除斜杠以外的任何内容.
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.
这篇关于Rails REST 路由:资源项 ID 中的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!