如何全局覆盖 rails url helper? [英] How can I globally override a rails url helper?
问题描述
我需要对 foo_path 添加一个简单的更改,所以我这样做了:
I needed to add a simple change to foo_path, so I did this:
module ApplicationHelper
# [...]
def foo_path(foo, options = {})
options.merge!(bar: foo.some_attribute)
super
end
# [...]
end
现在,这在从视图调用时有效,但从控制器调用时,将使用没有我添加的原始变体.
Now, this works when called from a view, but when called from a controller, the original variant without my additions is used.
如何覆盖应用范围内的相应帮助程序 (_path/_url)?
推荐答案
我认为最简洁的方法是自定义 routes.rb
文件(至少对于静态默认参数).文档:http://guides.rubyonrails.org/routing.html#customizing-resourceful-路由
I think the cleanest way to achieve that is to customize routes.rb
file (at least for static default parameters). Docs: http://guides.rubyonrails.org/routing.html#customizing-resourceful-routes
默认参数示例:
get "/foo(/:bar)" => "my_controller#index", defaults: { bar: "my_default" }
默认参数值示例 + 范围:
scope '/(:rec_type)', defaults: { rec_type: 'mammo' }, rec_type: /mammo|face/ do
resources :patients
end
其他选项(用于动态限制):
Other options (for dynamic restriccions):
高级路由约束:
如果您需要更多高级/动态限制,请查看本指南:http://guides.rubyonrails.org/routing.html#advanced-constraints.
If you need more advanced/dynamic restrictions, take a look to this guide: http://guides.rubyonrails.org/routing.html#advanced-constraints.
覆盖 default_url_options:
此外,您可以覆盖 default_url_options
方法以使用路由助手自动添加一些属性(参数):http://guides.rubyonrails.org/action_controller_overview.html#default-url-options.
Also, you can override default_url_options
method to automatically add some attributes (params) using routes helpers: http://guides.rubyonrails.org/action_controller_overview.html#default-url-options.
您可以通过在控制器中定义一个名为 default_url_options 的方法来设置 URL 生成的全局默认参数.这样的方法必须返回具有所需默认值的散列,其键必须是符号:
You can set global default parameters for URL generation by defining a method called default_url_options in your controller. Such a method must return a hash with the desired defaults, whose keys must be symbols:
class ApplicationController < ActionController::Base
def default_url_options(options = {})
if action_name == 'foo' # or other conditions
options[:bar] = 'your_defaults' # add here your default attributes
end
options
end
end
覆盖 to_param:
Rails 路由系统在模型上调用 to_param
以获取 :id
占位符的值.ActiveRecord::Base#to_param
返回模型的 id,但您可以在模型中重新定义该方法.例如,给定:
Rails routing system calls to_param
on models to get a value for the :id
placeholder. ActiveRecord::Base#to_param
returns the id of a model, but you can redefine that method in your models. For example, given:
class Product < ActiveRecord::Base
def to_param
"#{id}-#{title}"
end
end
这将生成:/products/254-Foo
这篇关于如何全局覆盖 rails url helper?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!