加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:57:58 所属栏目:百科 来源:网络整理
导读:我的路线中有以下内容: resources :users,:except = [:new,:create] do get 'friends',:as = :friends,:on = :member,:to = "users#friends"end 并在我的user.rb中: def to_param self.loginend 例如,当登录时使用点(例如“any.thing”)的用户来自facebook
我的路线中有以下内容:
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读