我有嵌套资源,如此
resources :users do
resources :widgets
end
当我有@widget
时,要从我的助手那里获得正确的路由,我需要使用user_widget_path(@widget.user, @widget)
有没有办法告诉rails自动从@widget
对象中拔出用户?所以我可以使用user_widget_path(@widget)
答案 0 :(得分:2)
没有自动方法可以做到这一点。但是你可以创建自己的应用程序助手,它非常直接。
答案 1 :(得分:2)
@apneadiving是完全正确的。但是你可以改进你的方法:
link_to "user", user_widget_path(@widget.user, @widget)
可以缩短:
link_to "user", [@widget.user, @widget]
<强> UPD 强>
您也可以根据需要重写user_widget_path
:
class ApplicationController < ActionController::Base
helper_method :user_widget_path
private
def user_widget_path(widget)
super(widget.user, widget)
end
end
您还应该重写edit_user_widget_path
,new_user_widget_path
。最好将其包装为外部模块。