簡體   English   中英

Rails 自動從路由助手中的嵌套資源中提取資源

[英]Rails automatically pull out resource from nested resources in routes helpers

我有這樣的嵌套資源

resources :users do
  resources :widgets
end

當我有@widget時,要從我的助手那里獲得正確的路由,我需要使用user_widget_path(@widget.user, @widget)有沒有辦法告訴 rails 自動從@widget object 中拉出用戶? 所以我可以只使用user_widget_path(@widget)

沒有自動的方法可以做到這一點。 但是您可以創建自己的應用程序助手,這很簡單。

@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 最好將其包裝為外部模塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM