簡體   English   中英

Rails:嵌套資源的路由助手

[英]Rails: route helpers for nested resources

我有嵌套資源如下:

resources :categories do
  resources :products
end

根據Rails指南

您還可以將url_for與一組對象一起使用,Rails將自動確定您想要的路徑:

 <%= link_to 'Ad details', url_for([@magazine, @ad]) %> 

在這種情況下,Rails會看到@magazine是一個雜志而@ad是一個廣告,因此將使用magazine_ad_path助手。 在像link_to這樣的幫助器中,您可以僅指定對象來代替完整的url_for調用:

 <%= link_to 'Ad details', [@magazine, @ad] %> 

對於其他操作,您只需要將操作名稱作為數組的第一個元素插入:

 <%= link_to 'Edit Ad', [:edit, @magazine, @ad] %> 

就我而言,我有以下代碼,它們功能齊全:

<% @products.each do |product| %>
  <tr>
    <td><%= product.name %></td>
    <td><%= link_to 'Show', category_product_path(product, category_id: product.category_id) %></td>
    <td><%= link_to 'Edit', edit_category_product_path(product, category_id: product.category_id) %></td>
    <td><%= link_to 'Destroy', category_product_path(product, category_id: product.category_id), method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %> 

顯然它有點太冗長了,我想用rails guide中提到的技巧來縮短它。

但是,如果我更改了顯示編輯鏈接,如下所示:

<% @products.each do |product| %>
  <tr>
    <td><%= product.name %></td>
    <td><%= link_to 'Show', [product, product.category_id] %></td>
    <td><%= link_to 'Edit', [:edit, product, product.category_id] %></td>
    <td><%= link_to 'Destroy', category_product_path(product, category_id: product.category_id), method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>

它們都不再起作用了,頁面抱怨同樣的事情:

NoMethodError in Products#index
Showing /root/Projects/foo/app/views/products/index.html.erb where line #16 raised:

undefined method `persisted?' for 3:Fixnum

我錯過了什么?

Rails“自動”知道使用哪條路徑的方法是檢查為其類傳遞的對象,然后查找名稱匹配的控制器。 因此,您需要確保傳遞給link_to幫助程序的內容是實際的模型對象,而不是像category_id那樣只是一個fixnum ,因此沒有關聯的控制器。

<% @products.each do |product| %>
  <tr>
    <td><%= product.name %></td>
    <td><%= link_to 'Show', [product.category, product] %></td>
    <td><%= link_to 'Edit', [:edit, product.category, product] %></td>
    <td><%= link_to 'Destroy', [product.category, product], method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>

我猜測違規行是其中之一:

<td><%= link_to 'Show', [product, product.category_id] %></td>
<td><%= link_to 'Edit', [:edit, product, product.category_id] %></td>

product.category_id是一個Fixnum ,並且路由不能知道隨機數應該映射到category_id

使用以前的URL,它們更具可讀性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM