两个路由为相同的操作Rails

时间:2017-12-21 03:31:55

标签: ruby-on-rails

我有一个应用程序,列出了主帐户下的所有子帐户。但是,当我点击子帐户时,我希望它转到accounts/1/subaccounts/1,而不是去subaccounts/1。当我使用for_each语句时,我收到以下错误。如何点击嵌套路线并将其转到subaccounts/1而不是accounts/1/subaccounts/1

enter image description here

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

的routes.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 个答案:

答案 0 :(得分:-1)

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

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

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

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

通过救援处理,您需要随处处理@account 您还可以在params[:account_id].present?时触发set_account方法,这也适合您。