我有一个School
模型,而不是我的网址是schools/1
,而不是我的网址是localhost:3000/IL/city/school_name
。
我遵循this guide来使用段塞创建自定义路由,但最终结果是一个看起来像这样的网址:
http://localhost:3000/schools/IL%2Fcicero%2Fabe-lincoln-elem-school
我想做两件事:1.从路线中删除“学校”,并2.将“%2F”替换为“ /”。
我已经在类似rake的任务中创建了子弹:
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
最后,在我的控制器中的show动作:
@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'
答案 0 :(得分:0)
我最终这样更改了路由文件:
httpcontext
然后,我更改了子弹脚本,以删除“ IL / city”位(并再次运行此rake任务以更新子弹):
resources :schools, :only => [:index, :new, :create, :edit]
resources :schools, :only => [:show], path: 'IL/:city/', param: :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)
我敢肯定,有更好的方法可以做到这一点,但这目前仍然有效。