简体   繁体   English

使用带有命名空间路由的link_to的rails

[英]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. 我已经创建了一组带有admin命名空间的路由和控制器,我在使用这些新路由的链接助手时遇到了一些问题。

I see that there are some new path helpers, such as admin_projects_path which leads to the /admin/projects. 我看到有一些新的路径助手,例如admin_projects_path,它通向/ admin / projects。 however, i'm having trouble linking to the show, edit, destroy, etc. paths for these objects within the namespace. 但是,我无法链接到命名空间中这些对象的show,edit,destroy等路径。 how do I do that? 我怎么做?

If you're using Rails 3 , you can use your admin namespace with the variable instead of writing the long helper path name. 如果您使用的是Rails 3 ,则可以将admin命名空间与变量一起使用,而不是编写长辅助路径名。

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]

You should see all of your routes listed in rake routes and you can use those by name to get the proper namespacing. 您应该看到rake routes路由中列出的所有rake routes ,您可以按名称使用这些rake routes来获取正确的命名空间。 Using the automatic detection where you pass in :controller and :action manually won't work as you've discovered. 使用传入的自动检测:controller:action不会像您发现的那样工作。

If it's listed as new_thing in the routes, then the method is new_thing_path with the appropriate parameters. 如果它在路由中列为new_thing ,则该方法是带有适当参数的new_thing_path 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)

Some methods require a :url option as a parameter, and in those cases you can use url_for to generate the path: 有些方法需要:url选项作为参数,在这种情况下,您可以使用url_for生成路径:

icon(:url => url_for(:controller => "admin/projects", :action => "edit", :id => @project),
     :type => :edit)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM