Rails自动从路由助手中的嵌套资源中提取资源

时间:2011-08-16 15:54:05

标签: ruby-on-rails ruby ruby-on-rails-3 routes

我有嵌套资源,如此

resources :users do
  resources :widgets
end

当我有@widget时,要从我的助手那里获得正确的路由,我需要使用user_widget_path(@widget.user, @widget)有没有办法告诉rails自动从@widget对象中拔出用户?所以我可以使用user_widget_path(@widget)

2 个答案:

答案 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_pathnew_user_widget_path。最好将其包装为外部模块。

相关问题