代码之家  ›  专栏  ›  技术社区  ›  Trenton Tyler

同一动作滑轨的两条路线

  •  0
  • Trenton Tyler  · 技术社区  · 8 年前

    我有一个应用程序,它列出了主帐户下的所有子帐户。但是,当我单击子帐户时 accounts/1/subaccounts/1 我想让它去 subaccounts/1 . 当我使用for\u each语句时,会出现以下错误。如何单击嵌套管线并使其 子科目/1 而不是 科目/1/子科目/1 ?

    enter image description here

    <% @subaccounts.each do |sa| %>
        <%= link_to "#{sa.name}", subaccount_path(sa) %>
    <% end %>
    

    路线。rb型

    resources :subaccounts
    
    resources :accounts do
      resources :subaccounts
    end
    

    子帐户控制器

    before_action :set_account, only: [:show, :edit, :new, :create]
    before_action :set_subaccount, only: [:show, :edit, :update, :destroy]
    
    def show
    end
    
    
    private
        def set_account
          @account ||= Account.find(params[:account_id])
        end
    
        def set_subaccount
          @subaccount ||= @account.subaccounts.find(params[:id])
        end
    
        def subaccount_params
          params.require(:subaccount).permit(:name, :state)
        end
    
    1 回复  |  直到 8 年前
        1
  •  -1
  •   Manishh    8 年前

    您面临的问题是由于控制器对两条不同的路线执行相同的操作。您可以通过为嵌套路由添加另一个控制器来修复它

    resources :accounts do
      resources :subaccounts, controller: 'accounts_subaccounts'
    end
    

    或处理异常并检查 @account (最不喜欢的方式/不良做法)

    @account ||= Account.find(params[:account_id]) rescue nil
    

    在处理rescue时,您需要在任何地方处理@account。
    您还可以在以下情况下触发set\u account方法: params[:account_id].present? 这对你也有用。