Search code examples
ruby-on-railsrouteslink-to

Can't link_to correct path when using nested shallow routes


I am using nested routes in my rails app. I am successfully able to link through to clients/:id/invoices/:id The problem I am running into I think is that I am using shallow routes, so after clicking an invoice show link my app redirects from /client/:id to /invoice/:id. Now when I try to go back from this show link to my client_path I get the two routes mixing up.

for example invoice/34 becomes client/34 when I try to link_to my client path when it should change to the clients id.

I think this might have something to do with my show action in my clients_controller being @client = Client.find(params[:id])

My routes

resources :clients do
resources :invoices, shallow: true
end

My clients controller show action

def show
@client = Client.find(params[:id])
@invoices = @client.invoices
end

Clients show.html.erb

<% @invoices.where(published: false).each do |invoice| %>
  <tr>
   <td><%= invoice.sender %></td>
   <td><%= invoice.reciever %></td>
   <td><%= invoice.amount %></td>
   <td><%= invoice.currency %></td>
   <td><%= invoice.date %></td>
   <td><%= link_to 'Show', invoice_path(invoice) %></td>
  </tr>                
<% end %>  

and my invoice show.html.erb

<%= link_to 'Back', client_path, class: "btn btn-primary" %>

Solution

  • I think the issue is client_path has no idea which Client to use, and it's defaulting to params[:id]. You probably want your link_to to look like this:

    <%= link_to 'Back', client_path(invoice.client), class: "btn btn-primary" %>

    Which explicitly states to use the Client associated with this Invoice.