代码之家  ›  专栏  ›  技术社区  ›  Bad Request

如何使rails view.erb文件打印URL的最后一部分?

  •  1
  • Bad Request  · 技术社区  · 15 年前

    我对铁轨是个新手。我已经学习了如何进行静态控制器操作和相应的视图文件。现在我想这样做,当我到localhost:3000/hi/anita时,页面会显示“hi anita”,但当我到localhost:3000/hi/bob时,页面会显示“hi bob”。当然,我不想让安妮塔和鲍勃采取行动。你明白了。有什么我该怎么做的提示吗?谢谢!

    1 回复  |  直到 15 年前
        1
  •  3
  •   PeterWong    15 年前

    我将首先定义接受“最后一部分”的路径,然后在操作中检索它:

    # in routes.rb
    # for rails 3:
    match "/hi/:who" => "static#say_hi"
    # for rails 2:
    map.connect "/hi/:who", :controller => "static", :action => "say_hi"
    
    # in StaticController
    def say_hi
      @who = params[:who] || "No body" # as the user can use the url "/hi" without the "last part"
    end
    
    # in views/static/say_hi.html.erb
    Hi <%= @who %>