如何制作Rails视图.erb文件打印URL的最后一部分?

时间:2010-10-14 05:05:14

标签: ruby-on-rails ruby dynamic

我是Rails的新品牌。我已经学会了如何制作静态控制器动作和相应的视图文件。现在我想做到这一点,当我去localhost:3000 / hi / anita时,页面上写着“Hi anita”,但是当我去localhost:3000 / hi / bob时,它会说“Hi bob”。当然,我不想做anita和bob动作。你明白了。有什么提示我怎么能这样做?谢谢!

1 个答案:

答案 0 :(得分:3)

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

# 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 %>