简体   繁体   中英

Rails string manipulation with routes

I have an app where users can register their own personal url like so

  • myapp.com/users-personal-url

I want to run through my rails config file and automatically grab the urls that are already in use, and iterate through these in a validation method to prevent users from reserving these urls. For example...

if in my routes file I have something like

match 'test' => 'courses#test'
resource :users

then users should not be able to register the "users" url or "test" url. So far I've found that I can grab all the routes inside a ruby class by using rake routes

But my string manipulation skills are failing me since I am a rails noob. Basically I need to substring the routes, place them in a collection and do the validation check. A pointer in the right direction or working code is appreciated. Thanks.

I don't think there is any quick Rails way of doing what you would like to do in the routes.rb.

You would need to create custom validators in your model.

In the model that handles user generated URL submissions, add this validator.

class Whatevermodel < ActiveRecord::Base
  validate :protect_reserved_url, :on => create

  def protect_reserved_url
    reserved_url = ['test', 'users', 'whatever_other_url_you_want_to_protect']
    if reserved_url.include?(url_submission.downcase)
      errors.add(:url_submission, "is an invalid URL")
    end
  end
end

Well to simply get the routes so that you can match them, this guy had a cool way of doing that how get all routes in my rails application?

https://stackoverflow.com/questions/3672554/how-get-all-routes-in-my-rails-application

Or you could break them down with

Rails.application.routes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM