Rails [Rails API] ApplicationController#default_url_options ()

zhlwish · September 07, 2012 · Last by hpyhacking replied at September 13, 2012 · 4632 hits

来自:http://kan.weibo.com/con/3487676393188469

在 RoR 应用中写 view 的时候,经常要写这样的代码:

<%=link_to 'link name', :controller => 'user' :action => 'view', :username => @user.name, :param2 => 'param2' %>

但是总会遇到所有的链接中都会添加某个参数的情况,比如上面例子中的 username 参数,难道每写一个link_to()或者url_for()都需要手动的写上这个参数么?

当然不,Rails 提供了一种设置全局 URL 参数的方法,只要在你的ApplicationController中加上default_url_options()方法就行了,这个方法返回一个 Hash,我们可以在这个 Hash 中加入我们的全局 URL 参数就可以了,比如:

class ApplicationController < ActionController::Base def default_url_options() {:user=> @user.username} end end

这样之后,在 view 中的link_to()url_for()以及其他生成 URL 的方法都会自动加上这个参数。

详见:http://guides.rubyonrails.org/action_controller_overview.html#default_url_options

全局参数的同时可以使用 xxx_path xxx_url 这种幽灵方法

You need to Sign in before reply, if you don't have an account, please Sign up first.