简体   繁体   English

Rails:使用链接的资源构建link_to链接

[英]Rails: Building a link_to link with nested resources

I have three models in my routes.rb : 我的route.rb中有三个模型:

  resources :products do
    resources :departments, :revenues
  end

I'm trying to link to a product's department from the department show.html like this: 我正在尝试从部门show.html链接到产品部门,如下所示:

<% @products.each do |product| %>
      <%= link_to product_department_path(:id => product.id) do %><li><%= product.name %></li><% end %>
    <% end %>

What this is doing is giving me HTML like this: 这是在给我这样的HTML:

<ul>

      <a href="/products/2/departments/1"><li>Product1</li></a>
      <a href="/products/2/departments/2"><li>Product2</li></a>
      <a href="/products/2/departments/3"><li>Product3</li></a>
      <a href="/products/2/departments/5"><li>Product4</li></a>

  </ul>

What I really need is this: 我真正需要的是:

<ul>

      <a href="/products/1/departments/"><li>Product1</li></a>
      <a href="/products/2/departments/"><li>Product2</li></a>
      <a href="/products/3/departments/"><li>Product3</li></a>
      <a href="/products/4/departments/"><li>Product4</li></a>

  </ul>

Your code is a little verbose, so I have simplified it. 您的代码有点冗长,因此我简化了它。 I think you want product_departments_path 我想你想要product_departments_path

<li>
  <%= link_to product.name, product_departments_path(product) %>
</li>

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

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