Search code examples
ruby-on-rails-5nested-resources

Link_to helper: Nested Routes


This driving me crazy...

I've built some test apps with standard routing, but this time wanted to nest b within a. So like this (a and b are examples for ease)

resources :a do
 resources :b
end

in the 'b controller' I have index defined as

def index
 @b = B.all
end

On the index page I have

<p>B index</p>
 <ul class="b">
  <% @b.each do |b| %>
  <li>
   <%= link_to b.name, b %>
  </li>
<% end %>

Controller params are set

  def B_params
    params.require(:b).permit(:name, :description, :this, :that, :a_id)
  end    

So the error message is when viewing the index.html 'undefined method for b_path'

I'm pretty sure its a routing problem as all of my other index pages work fine. So what is the correct way to route the nested b_path.

I have tried

get '/a/:id/b', to: 'b#index' -----fails
get '/a/:a_id/b', to: 'b#index' ----fails
get '/b', to: 'b#index' ----- not surprising fails

So what am I missing. Is there something else to do or another way of linking once you nest resources

Thanks


Solution

  • OK so I managed to figure this out after what feels like an eternity. Just in case anyone is interested

    The fault lied with the reference to 'b' immediately after the link_to b.name statement. It should have been...

    <p>B index</p>
     <ul class="b">
     <% @b.each do |b| %>
     <li>
     <%= link_to b.name, a_b %>
     </li>
    

    So to explain, as I understand it. The three important files once nested are routes.rb where you need to set the correct route for the index... for this example it would be

    get '/a/:a_id/b', to: 'b#index'
    

    this comes from running rails routes and seeing the correct path returned there.

    Then in the 'b controller' you declare the variable as normal

    def index
        @b = B.all
    end
    

    then in the view/b/index.html.erb you call the variable, but crucially refer to the new b#index path

    <% @b.each do |b| %>
      <li>
      <%= link_to @b.name, a_b_url %>
      </li>
    <% end %>
    

    I'm sure my understanding is not as complete as it could be yet but i've got it working so onwards and upwards. Happy days