如何解决没有路由匹配 {:action=>"show", :controller=>"products"},缺少必需的键:[:id]
索引路由将有一个在索引路由中不存在的 :id
。
我有干净的路线:
resources :products
这是控制器,
class ProductsController < ApplicationController
before_action :set_product,only: [:show]
skip_before_action :authorize_request,only: [:show,:index]
# GET /products
def index
# params here {"controller"=>"products","action"=>"index","product"=>{}}
@products = Product.all
render json: @products
end
ActionController::UrlGenerationError: No route matches {
:action=>"show",:controller=>"products"},missing required keys: [:id]
为什么叫“show”?我没有将任何参数传递给控制器: 这是规范:
RSpec.describe "/products",type: :request do
describe " GET /index" do
it " renders a successful response " do
Fabricate.times(3,:product)
get "/products",headers: valid_headers
expect(response).to be_successful
end
end
end
当我从 get "/products",to: 'products#index'
更改路由并注释掉 resources :products
时,它通过了测试
发现编辑/问题:
我在我的产品模型中使用了 include Rails.application.routes.url_helpers
,这导致了这个问题。我需要它来生成 URL 来检索我的附件。我还能如何获得 ActiveStorage
的网址?
解决方法
我解决了这个问题:我的产品模型中有 include Rails.application.routes.url_helpers
导致了这个问题:
class Product < ApplicationRecord
# include Rails.application.routes.url_helpers
end
注释掉,所有规范都通过了
但我仍然不明白为什么我不能在我的模型中使用它。
我想包含它来检索我的附件的网址:
def main_image_thumb_url
rails_blob_url(main_image,host: "localhost:3000")
end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。