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

问题描述 投票:0回答:1

我有一个School模型,而不是在schools/1的网址我想在localhost:3000/IL/city/school_name有网址。

我跟着this guide使用slug创建自定义路由,但最终结果是一个如下所示的url:

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

我想做两件事:1。从路线上放下'学校',然后用“/”替换%2F。

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

  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'
ruby-on-rails slug custom-routes
1个回答
0
投票

我最终改变了我的路线文件,如下所示:

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

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

  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: ''))

我确信有更好的方法可以做到这一点,但现在这样做。

© www.soinside.com 2019 - 2024. All rights reserved.