【问题标题】:Rails routing / clipping mistyped urlsRails 路由/剪裁错误输入的 url
【发布时间】:2014-01-28 10:38:26
【问题描述】:

在我的路由器中我有:

get 'cars/:make', to: 'cars#make'

当人们访问 /cars/dodge 或 /cars/toyota 时,这可以正常工作,但是当人们进入 /cars/make-does-not-exist 时,我更喜欢页面 drop 'make-does-not-exist' from url,并将它们发送到 /cars。

在我的 cars#make 控制器中,我有一些逻辑可以正确设置我的视图:

def make
 case params[:make]
   when "dodge"
    @text = "dodge text"
   when "toyota"
    @text = "toyota text"
   else
    @text = "default text"
    #how do I send people to /cars, and not /cars/make-does-not-exist
 end
 render :index  #render index with the @text that we just set
end

如何从控制器设置 url?

谢谢!

【问题讨论】:

标签: ruby-on-rails routes url-routing


【解决方案1】:

为了能够将人们重定向到/cars,您必须添加到您的路线

get 'cars', to: 'cars#make'

然后修改你的控制器看起来更像

def make
 case params[:make]
   when nil
    @text = "default text"
   when "dodge"
    @text = "dodge text"
   when "toyota"
    @text = "toyota text"
   else
    wrong_make = true
 end
 if defined? wrong_make
   redirect_to 'cars'
 else
   render :index
 end
end

希望有帮助

【讨论】:

  • 感谢这项工作。一个注释:我必须使用redirect_to '/cars'(添加了一个斜线)。
猜你喜欢
  • 1970-01-01
  • 2010-12-26
  • 1970-01-01
  • 2012-05-22
  • 2012-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多