【问题标题】:Problem with link to associated object's show action关联对象的显示操作的链接问题
【发布时间】:2019-01-17 06:36:05
【问题描述】:

我正在尝试呈现包含指向“产品”页面链接的部分内容,该页面属于某个类别。如果我使用 link_to 方法的数组语法,我能够生成指向产品展示页面的链接,但是在我的表格底部有一个额外的链接可以转到产品索引页面。

我目前正在使用 link_to 方法的数组语法来创建指向产品展示页面的链接。它可以工作,但在表格底部有一个额外的链接指向产品的索引页面。如果不存在产品,则该链接仍然存在于它自己的行中。如果产品确实存在,则链接将位于表格底部的空行中。

部分

<tr>
  <td>
    <%= product.product_name %>
  </td>
  <td><%= product.product_description %></td>
  <td><%= product.product_price %></td> 
  <td><%= link_to 'Product page', [@category, product] %></td>
</tr>

景色

  <table>
    <tr>
      <th>Product Name</th>
      <th>Product Description</th>
      <th>Product Price</th>
    </tr>
    <%= render @category.products %>
  </table>

显示产品控制器的操作

  def show
    @category = Category.find(params[:category_id])
    @product = Product.find(params[:id])
  end

产品的展示路线

category_product GET    /categories/:category_id/products/:id(.:format)                                          products#show

产品路线截图 output of rake routes | grep product

routes.rb

Rails.application.routes.draw do
  root 'pages#index'
  get 'pages/admin'
  get 'show_customer/:id', to: 'categories#show_customer', as: :show_category_to_customer

  resources :categories do
    resources :products
  end

  resources :users
end

我想要一个表,其中仅包含指向产品展示页面的链接,而不是指向产品索引页面的额外链接。我在部分中尝试了 category_product_path(@category, product),但我得到一个 URLGenerationError 说产品 ID 为 nil。

对于如何在不获取额外链接的情况下生成链接的任何帮助,我将不胜感激。

【问题讨论】:

  • 你能展示你的部分吗?
  • 全部部分添加到答案

标签: ruby-on-rails ruby-on-rails-5


【解决方案1】:

您的路径需要产品的 ID,但您提供的是未初始化的变量“产品”。 试用 category_product_path(@category,@product)

【讨论】:

  • 我更新了我的答案以包括完整的部分。产品变量在部分的其他任何地方都有效,并且也适用于产品展示页面的链接。问题是指向产品索引页面而不是显示页面的额外链接。
【解决方案2】:
<tr>
  <td>
    <%= product.product_name %>
  </td>
  <td><%= product.product_description %></td>
  <td><%= product.product_price %></td> 
  <td><%= link_to 'Product page',  category_product_path(category_id: @category.id, id: product.id)%></td>
</tr>

【讨论】:

  • 当我使用它时,我收到以下错误 'ActionController::UrlGenerationError in Categories#show' 'No route matches {:action=>"show", :category_id=>1, :controller=> "products", :id=>nil}, 可能的不匹配约束:[:id]'
  • 能否在项目目录rake routes | grep product的控制台上运行代码并显示结果。
  • 我在问题中添加了输出的屏幕截图。
  • @user9347240 不知道为什么我认为您的路线中有一些拼写错误,因为我可以看到给定的路径应该看起来像 products#show 而它正在寻找 categories#show
  • @user9347240 你介意显示你的routes.rb吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 2018-11-24
相关资源
最近更新 更多