【问题标题】:Check for the existence of multiple params检查是否存在多个参数
【发布时间】:2011-01-27 22:54:57
【问题描述】:

我正在创建一个输入表单,我希望只有在三个 url 参数就位时才能访问它:example.com/entries/new/2011/01/27 如果有人尝试访问任何其他 url(即example.com/entries/newexample.com/entries/new/2011/),我希望 Rails 能够设置 :alert 并将用户弹回索引页面。

目前,我的 routes.rb match '/entries/new/:year/:month/:day' => 'entries#new' 中只有此代码。如果正确的参数不在 URL 中,我需要做什么来控制重定向?我会检查控制器中的每个参数,然后执行redirect_to,或者这是我可以从 routes.rb 文件中专门做的事情吗?如果是前者,是否有更简单的方法来检查所有三个参数是否存在,除了:

if params[:year].nil && params[:month].nil && params[:day].nil redirect_to ...

【问题讨论】:

  • 您可能没有得到很多答案,因为这不是正常的做事方式。通常,URL 将是 example.com/entries/create?date=2011-01-27 或 example.com/entries/create?year=2011&month=1&day=27,您不会处理所有路由内容。然后,您可以使用验证来检查参数。

标签: ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

这条路线需要所有三个参数都存在:

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,它将重新定义indexnew

更多信息可以在指南Routing From the Outside In 中找到。使用日期参数时,约束是个好主意(第 4.2 节)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 2021-08-22
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多