Rails REST routing: dots in the resource item ID

前端 未结 3 1355
清歌不尽
清歌不尽 2020-12-15 20:30

I have following in my routes.rb:

resources :users, :except => [:new, :create] do
    get \'friends\', :as => :friends, :on => :member, :to => \"         


        
相关标签:
3条回答
  • 2020-12-15 20:45

    To allow the :id segment to contain any character except '/':

    match 'users/(:id)' => 'users#show', :constraints => {:id => /[^\/]+/}
    

    It's written elsewhere in one of the answers, but this is IMO the simplest way.

    0 讨论(0)
  • 2020-12-15 20:49

    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"
    

    EDIT

    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\-\.]+/ }
    

    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.

    Note that this is mentioned in the Rails Routing Guide, section 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.

    0 讨论(0)
  • 2020-12-15 20:52

    The following constrain definition permit the dot in id as well as any character except slash.

    Supported formats must be explicitly defined (here .html and .json) to not to be taken by id.

    resources :foobars,
      :constraints => { :id => /[^\/]+(?=\.html\z|\.json\z)|[^\/]+/ }
    

    That constrain definition is worked with Rails 3.1

    For earlier Rails versions you may need to backport look-ahead support in regin gem (it is vendored in rack-mount gem)

    0 讨论(0)
提交回复
热议问题