我總是在這個 Ruby 檔案中的 Rails 專案中遇到路由錯誤。它向我顯示了路由錯誤,如下面的螢屏截圖所示。
所有 gems 都安裝正確,它向我顯示主頁,但不向我顯示檢查檔案或顯示檔案頁面。
這是我的 Routes.rb 代碼:
Rails.application.routes.draw do
get 'home/submission3'
post 'home/checkFile'
get 'home/showFiles'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
這是顯示的錯誤影像:

這是我的控制器代碼:
# C:\Users\attari\RubymineProjects\submission3\app\controllers\home_controller.rb
require 'docx'
require 'find'
class HomeController < ApplicationController
def submission3
end
def checkFile
word = params[:folder][:word]
path = params[:folder][:path]
@files = checkWord(word, path)
puts "FILES ARE #{@files}"
redirect_to home_showFiles_path(@files)
# puts "WORD IS #{word} PATH IS #{path}"
end
def save
@submissions = submission3.new
end
def checkWord(userInput, folderInput)
count = 0
if (Dir.exist?(folderInput))
docx_file_paths = []
filtered_files = []
Find.find(folderInput) do |path|
docx_file_paths << path if path =~ /.*\.docx$/
end
(0..docx_file_paths.length - 1).each { |i|
d = Docx::Document.open(docx_file_paths[i])
d.each_paragraph do |p|
string_ = p.to_s()
if (string_.include? userInput)
puts docx_file_paths[i]
filtered_files.append(docx_file_paths[i])
count = count 1
puts count
else
puts "No word Matched"
end
end
puts count
}
return filtered_files
else
puts "No Directory exist"
end
end
def create
@submission3 = submission3.new(params[:word])
if @submission3.save
redirect_to new_submission_path
end
end
private
def book_params
params.require(:book).permit(:title)
end
end
如何修復此 routes.rb 錯誤?
uj5u.com熱心網友回復:
如果查看錯誤訊息,您可以看到檔案名直接附加到路由名稱 ( /home/showFiles.C:\Users...)。您需要向路由添加一個 id,以便 Rails 知道在那里期待什么。您的路線應如下所示:
get 'home/show_files/:file_name'
[請注意,您需要:file_name在將訪問的背景關系中定義(您的控制器)。]
更好的是使用模型作為路線的基礎。所以,如果你有(例如)一個 File 模型,你可以使用:
resources :files
Rails 會自動為你生成一大堆路由(或者你可以通過執行類似的操作來限制路由resources :files, only: [:show, :index, :create, :delete])。
基本上,我認為您需要閱讀更多有關 Rails 和路由應該如何作業的資訊。RailsGuides可能是一個很好的起點。如果您使用Rails 及其約定,您會發現您的生活容易得多!Rails 更喜歡約定而不是配置!
此外,在一個附帶問題上,您在命名方法和變數時沒有遵循 Rails 約定。CamelCase 用于物件名稱(如class HomeController),但不用于方法名稱或變數名稱 - Rails 為這些名稱使用 snake_case。同樣,如果您堅持使用 Rails 約定(例如,show_files不是showFiles),您會發現事情變得更加順利。遵循 Rails 約定意味著 Rails 會為您無縫拼接;不遵循它們,Rails 將是一場徹頭徹尾的噩夢。
uj5u.com熱心網友回復:
根據錯誤,/submission3即使您已經定義了/home/submission3路由,您似乎也在嘗試訪問路由。更新路由應該可以修復你的路由錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/317058.html
