【问题标题】:Rails 3.1 - How to redirect properly with custom routesRails 3.1 - 如何使用自定义路由正确重定向
【发布时间】:2011-10-11 15:13:35
【问题描述】:

我有一个带有“customURL”字段的 Pages 模型。我可以在 '/:customurl' 做 page#show。但是因为我已经在路由中定义了页面显示方式,所以我的创建操作现在会在成功时重定向到错误的路由。我应该更改什么以最干净地正确修复重定向以在保存时指向“/:customurl”?

控制器:

def create
  @page = Page.new(params[:page])

  respond_to do |format|
    if @page.save
      format.html { redirect_to page_url, notice: 'Page was successfully created.' }
      format.json { render json: @page, status: :created, location: @page }
    else
      format.html { render action: "new" }
      format.json { render json: @page.errors, status: :unprocessable_entity }
    end
  end
end

路线:

resources :pages
...
get "/:customURL" => "pages#show"

谢谢!

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    routes.rb,你可以添加魔法助手。

    get "/:customURL" => "pages#show", :as => :custom
    

    然后在你的控制器中

    format.html { redirect_to custom_url(@page. customURL), notice: ... }
    

    现在,"/:customURL" 需要在您的 routes.rb 中最后,路由是贪婪的,第一个匹配的会得到它。因此,如果您有类似“/bob”之类的内容,并且您有一个控制器正在监听“/bob”,那么控制器将在页面控制器之前获取它。

    【讨论】:

    • 好的,嗯,这正在使我的服务器崩溃。我在日志中得到了这个:Exiting .../config/routes.rb:18:in block in ': undefined local variable or method custom' for #<ActionDispatch::Routing::Mapper:0x000001012054e8> (NameError) 让我知道我是否需要这里的 tweek 或者您可能需要更多代码...需要在某处添加路线助手或其他东西吗?
    • 好的,使用你所拥有的,我能够将它拼凑起来。这对我有用,也许相应地编辑您的答案?在路由中:get "/:customURL" => "pages#show", :as => :pageshow 和在控制器中 format.html { redirect_to pageshow_path(@page.customURL),...
    • 抱歉,我是as: :custom。我会解决的!
    • 你能在我的评论中添加其他内容吗?如果您想使用自定义而不是“页面显示”,那很酷。换句话说,只需将其设为 :as => 并执行 @page.customURL?无论如何,这对我有用。再次感谢。
    • 当然,:as => :custom 与较新的 ruby​​ 中的 as: :custom 相同。除了散列火箭 (=>) 之外,Ruby 添加了 JSON 样式 (?) 散列标识符。不过,我很乐意调整。很高兴你成功了。
    猜你喜欢
    • 2017-05-14
    • 2018-10-14
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多