检查是否存在多个参数
我正在创建一个条目表单,我希望只有在三个url参数存在时才可以访问:example.com/entries/new/2011/01/27
如果有人试图访问任何其他url(即example.com/entries/new
或example.com/entries/new/2011/
)我希望Rails设置:提醒并将用户退回到索引页面。检查是否存在多个参数
目前,我只有这个代码在我的routes.rb match '/entries/new/:year/:month/:day' => 'entries#new'
。如果适当的参数不在URL中,我需要做些什么来控制重定向?我会检查控制器中的每个参数,然后执行一个redirect_to
,或者这是我可以从routes.rb文件专门做的事情吗?如果是前者,有检查,所有这三个PARAMS存在其他比一个简单的方法:
if params[:year].nil && params[:month].nil && params[:day].nil redirect_to ...
这条路线需要所有三个参数的存在:
match '/entries/new/:year/:month/:day' => 'entries#new'
由于只有这条路,GET /entries/new
将导致:
No route matches "/entries/new"
您可以从routes.rb
这样的内重定向:
match '/entries' => 'entries#index'
match '/entries/new/:year/:month/:day' => 'entries#new'
match "/entries/new/(*other)" => redirect('/entries')
第二行匹配所有三个参数都存在的路径。第三行使用“路由通配”匹配所有其他/entries/new
的情况,并执行重定向。第三行匹配的请求将不会命中EntriesController#new
。
注意:您可能不需要在第一行,如果你已经定义的路线EntriesController#index
- 但要注意resources :entries
,这将重新定义index
和new
。
更多信息可以在指南中找到Rails Routing From the Outside In。在使用日期参数时,限制是一个好主意(第4.2节)
您可能得不到很多答案,因为这不是正常的做事方式。通常,该网址将为example.com/entries/create?date=2011-01-27或example.com/entries/create?year=2011&month=1&day=27,并且您不会处理所有路由选择。然后您可以使用验证来检查参数。 – 2011-01-28 00:24:22