如何在rails中的URL中显示友好名称

时间:2014-03-16 12:41:19

标签: ruby-on-rails ruby-on-rails-4 routes

这是路径文件中的新资源:

resources :staticpage do
    collection do
            get :aboutus 
            get :snacks 
            get :contactus
    end
end

这会生成我的网址localhost:3000/staticpage/aboutus localhost:3000/staticpage/snacks/ localhost:3000/staticpage/contactus

我想在网址中添加localhost:3000/aboutuslocalhost:3000/snacks/ localhost:3000/contactus,而不是这个复杂的网址。

使用gem可以改变我的动作名称,但我想改变" controllername / action"一个简单的字符串。 应该在路径路径声明中做什么修改?

2 个答案:

答案 0 :(得分:2)

您可以像这样简单地为每条路线编写匹配器:

get 'aboutus', to: 'staticpage#aboutus'
get 'snacks', to: 'staticpage#snacks'
get 'contactus', to: 'staticpage#contactus'

请注意,如果您这样做,则不需要resourcescollection阻止。

答案 1 :(得分:0)

根据routes documentation,您需要手动定义路线(例如David Underwood的回答)。但是,有一种更好的方法:

#config/routes.rb
static = %w(aboutus snacks contactus)
static.each do |page|
   get page.to_sym, to: "staticpage#show", page: page
end

#app/controllers/staticpages_controller.rb
def show
    page = params[:page]
    render "staticpages#{page}"
end