简体   繁体   English

Rails 4中的link_to语法用于嵌套资源

[英]link_to syntax in Rails 4 for nested resources

I really don't understand how to link to another view in rails. 我真的不明白如何在Rails中链接到另一个视图。

I load datas in /products/index.html.erb and want to retrieve product id form one product to point to another view : subjects/index.html.erb 我将数据加载到/products/index.html.erb中,并希望从一种产品中检索产品ID以指向另一种视图:subjects / index.html.erb

what is the correct syntax to have this url with the link_to : '/products/9/subjects' (for product id 9) ? 将此URL与link_to一起使用的正确语法是什么:'/ products / 9 / subjects'(对于产品ID 9)?

Many thanks ! 非常感谢 !

如果您将嵌套路由定义为您的问题,则如下所示:

<%= link_to "Click", [@product, :subjects] %>
link_to "Click", subjects_product_path(9)

If you use rake routes it'll tell you which routes you have available you'd need nested resources for this to work 如果您使用rake路由,它将告诉您可用的路由,您需要嵌套资源才能使用

resources :products do
  resources :subjects
end

In your case: 在您的情况下:

<%= link_to "The name of your link", product_subjects_path(9) %>

Where 9 is the id of your product. 其中9是您的产品ID。 You can use more generic link like: 您可以使用更多通用链接,例如:

<%= link_to "The name of your link", product_subjects_path(@product) %>

in a show view of a product, or even: 在产品的展示视图中,甚至:

<h2>Links to subjects for each product </h2>

<% @products.each do |product| %>
    <%= link_to product.title, product_subjects_path(product) %>
<% end %>

in an index. 在索引中。

Assuming that in your routes you have subjects nested under products: 假设您的路线中的主题嵌套在产品下:

resources :products do
  resources :subjects
end

Don't forget when you are lost with your routes: 不要忘记何时迷路:

bundle exec rake routes

will give you all existing routes. 将为您提供所有现有路线。

Here is the rails guide about routing with nested: doc 这是有关使用嵌套进行路由的rails指南: doc

Here is the documentation for the syntax of the path: doc 这是路径语法的文档doc

To see all the routes in your rails application just use the following command: 要查看rails应用程序中的所有路线,只需使用以下命令:

rake routes

It will list all the routes along with the routes variables and the controller/action that they point to. 它将列出所有路由以及路由变量及其指向的控制器/操作。 From there you take the name of the route and append an _path or _url (in case you neeed an absolute url) in roder to obtain the name of the method to use in the link_to. 从那里获取路由的名称,并在roder中附加_path或_url(以防您输入了绝对URL),以获取要在link_to中使用的方法的名称。

In your case the link_to for the /products/9/subjects path is: 在您的情况下,/ products / 9 / subjects路径的link_to为:

link_to 'Link text', product_subjects_path(@product)

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

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