Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails using link_to with namespaced routes

I've created a set of routes & controllers with the admin namespace, and I was having some issues using the link helpers with these new routes.

I see that there are some new path helpers, such as admin_projects_path which leads to the /admin/projects. however, i'm having trouble linking to the show, edit, destroy, etc. paths for these objects within the namespace. how do I do that?

like image 628
GSto Avatar asked Nov 24 '10 17:11

GSto


3 Answers

If you're using Rails 3, you can use your admin namespace with the variable instead of writing the long helper path name.

view:

<td><%= link_to 'Show', [:admin, project] %></td>
<td><%= link_to 'Edit', [:edit, :admin, project] %></td>
<td><%= link_to 'Destroy', [:admin, project], confirm: 'Are you sure?', method: :delete %></td>

controller:

redirect_to [:admin, @project]
like image 133
rxgx Avatar answered Nov 20 '22 04:11

rxgx


You should see all of your routes listed in rake routes and you can use those by name to get the proper namespacing. Using the automatic detection where you pass in :controller and :action manually won't work as you've discovered.

If it's listed as new_thing in the routes, then the method is new_thing_path with the appropriate parameters. For instance:

link_to('New Project', new_admin_project_path)
link_to('Projects', admin_projects_path)
link_to(@project.name, admin_project_path(@project))
link_to(@project.name, edit_admin_project_path(@project))
link_to(@project.name, admin_project_path(@project), :method => :delete)
like image 43
tadman Avatar answered Nov 20 '22 05:11

tadman


Some methods require a :url option as a parameter, and in those cases you can use url_for to generate the path:

icon(:url => url_for(:controller => "admin/projects", :action => "edit", :id => @project),
     :type => :edit)
like image 1
jackpipe Avatar answered Nov 20 '22 06:11

jackpipe