ruby - Rails: route helpers for nested resources -


i have nested resources below:

resources :categories   resources :products end 

according rails guides,

you can use url_for set of objects, , rails automatically determine route want:

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

in case, rails see @magazine magazine , @ad ad , therefore use magazine_ad_path helper. in helpers link_to, can specify object in place of full url_for call:

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

for other actions, need insert action name first element of array:

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

in case, have following code functional:

<% @products.each |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 sure?' } %></td>   </tr> <% end %>  

obviously little verbose , wanted shorten using trick mentioned above rails guides.

but if changed show , edit link follows:

<% @products.each |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 sure?' } %></td>   </tr> <% end %> 

neither of them works more, , pages complains same thing:

nomethoderror in products#index showing /root/projects/foo/app/views/products/index.html.erb line #16 raised:  undefined method `persisted?' 3:fixnum 

what did miss?

the way rails 'automagically' knowing path use inspecting objects pass classes, , looking controller name matches. need make sure passing link_to helper actual model object, , not category_id fixnum , therefore has no associated controller.

<% @products.each |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 sure?' } %></td>   </tr> <% end %> 

Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -