ruby-on-railsrubyrouteslink-tolink-to-function

How to use "link_to" in an Admin section correctly in Rails


So I have an app which has an admin section. The admin section has a challenges controller with an index method and a view index.

I have also a challenges controller seperate from the admin folder. This controller has the whole CRUD.

Every challenge belongs_to a subject. The controller subjects in the admin section has an index method and view. The controller subjects not in the admin section has the whole CRUD.

Now, in the view of subjects (NOT the admin section), I can do something like:

<%= link_to "New Challenge".html_safe, new_subject_challenge_path(@subject) %>

I would like to do the same in the admin-section, but I can't really figure out how to do it. Copying the code throws me an error:

No route matches {:action=>"new", :controller=>"challenges", :subject_id=>nil} missing required keys: [:subject_id]

But I was hoping I could do this without additional routes....

It seems like it should be easy but I don't really know how to handle this. Any help would be very much appreciated... I hope I explained myself well enough.

The admin routes are used with a namespace:

namespace :admin do
    resources :paths, only: [:index, :new, :create, :update, :edit]
    resources :users, only: [:index, :new, :create, :show, :edit, :update] 

end

  resources :challenges, except: [:index, :destroy] do
    resources :solutions, only: [:create]
   end

resources :subjects

Solution

  • The link you are creating points to a route that requires a subject id. In the subjects view it works because Rails can find the subject_id in the @subjectthat you are passing to the path helper.

    When you copy and try to re-use the same link in your admin view, I expect that @subject is not assigned and so it cannot find the required subject_id. Provide your admin section view with the subject and it should work!

    Also if you want to get a clearer idea of routing, the Rails docs are pretty great.