Rails 5 自定义路由:如何创建自定义路径并用正斜杠替换 %2F

Rails 5 Custom Routes: how to create custom path and replace %2F with forward slash

我有一个 School 型号,而不是 schools/1 的 url 我想要 localhost:3000/IL/city/school_name 的 url。

我按照 this guide 使用 slug 创建自定义路由,但最终结果是 url 看起来像这样:

http://localhost:3000/schools/IL%2Fcicero%2Fabe-lincoln-elem-school

我想做两件事:1. 从路由中删除 'schools' 和 2. 将 %2F 替换为“/”。

我在这样的 rake 任务中创建了 slug:

  def to_slug(string)
    string.parameterize.truncate(80, omission: '')
  end

  slugs = []
  School.find_each do |school|
    slug = "#{school.state}/#{to_slug(school.city)}/#{to_slug(school.name)}"
    if slugs.include?(slug)
      slug = slug + "-2"
      p "Same Name"
    end
    p slug
    slugs << slug
    school.slug = slug
    school.save
  end

在我的学校模型中:

def to_param
    slug
  end

在我的 routes.rb:

resources :schools, param: :slug

最后,在我的控制器中显示动作:

@school = School.find_by_slug(params[:slug])

我是初学者,远远超出了我的技能范围。我已经阅读了很多关于路线的文章,看来我在路线中需要这样的东西:

get ':state/:city/:slug', to: 'schools#show'

我试过了,没用:

resources schools, except: show, param :slug

 get ':state/:city/:slug', to: 'schools#show'

我最终像这样更改了我的路由文件:

resources :schools, :only => [:index, :new, :create, :edit]
resources :schools, :only => [:show], path: 'IL/:city/', param: :slug

然后我更改了 slug 脚本以像这样删除 'IL/city' 位(并且 运行 这个 rake 任务再次更新 slugs):

  def to_slug(string)
    string.parameterize.truncate(80, omission: '')
  end

  slugs = []
  School.find_each do |school|
    slug = to_slug(school.name)
    if slugs.include?(slug)
      slug = slug + "-2"
      p "Same Name"
    end
    p slug
    slugs << slug
    school.slug = slug
    school.save
  end

然后哪里有 link_to(school.name, school) 我就得改成这样:

link_to(school.name, school_path(slug: school.slug, city: school.city.parameterize.truncate(80, omission: ''))

我确定有更好的方法来执行此操作,但目前有效。